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

查询某个字符在字符串中出现的次数,可用于查询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" );
}

你可能感兴趣的:(C++基础知识,class)