查询某个字符在字符串中出现的次数

字符串字符计数方法
本文介绍了一种在C++中统计字符串中特定字符出现次数的方法。通过使用STL中的find函数迭代查找目标字符,并记录其出现次数。此外,还提供了一个通用的模板函数用于不同数据类型的数据结构中元素的计数。

查询某个字符在字符串中出现的次数,可用于查询string,char类型的查询,然后用类模板实现了

#include "iostream"
using namespace std;

//字符串查询某个字符的出现的次数
int count(const string &s, char c)
{
    int n = 0;
    string::const_iterator i = find(s.begin(), s.end(), c);
    while (i != s.end())
    {
        ++n;
        i = find(i + 1, s.end(), c);
    }
    return n;
}

//类模板的实例化查询模板类出现的次数
template<class C, class T>int Count(const C &v, T val)
{
    typename C::const_iterator i = find(v.begin(), v.end(), val);
    
    int n = 0;
    while (i != v.end())
    {
        ++n;
        ++i;
        i = find(i, v.end(), val);
        
    }
    return n;
}


void main()
{
    const string str = "abcabcdfsafascfaf";
    char c = 'c';
    int n = Count(str, c);
    int b = count(str, c);
    cout << "字符串里面出现c的个数是:" << n << endl;
    
    
    system("pause");
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值