C++统计字符串中的小字符串个数

问题:
如何查找字符串中的小字符串个数?
比如在字符串   "abcadfbcaebf "       中   查找   'b '的个数或     "ca "的个数
===================================================================================
写法一:
int   Substr(CString   str,CString   sub)
{
int   nRet=   0,   nStart   =   0;
while(-1!=(nStart=str.Find(sub,nStart)))
{
nStart+=sub.GetLength();
++nRet;
}
return   nRet;
}


usage:
int   n=Substr( "abcadfbcaebf ", "b ");
int   n=Substr( "abcadfbcaebf ", "ca ");
 
==================================================================
另外一种写法:
 
CString   str;
str   =   "abcadfbcaebf ";
int   nCount1=0,   nCount2=0;
for(int   i=0;   i <str.GetLength();   i++)
{
if(str[i]   ==   'b ')
nCount1++;
}
while(   !str.IsEmpty()   )
{
int   index;
if(   (index   =   str.Find( "ca "))   !=   -1)
{
nCount2++;
str   =   str.Mid(index+2);
}
else
break;
}
============================================================================================
写法三:使用Hash表,Map:http://wenwen.soso.com/z/q278570518.htm
 
#pragma warning(disable:4786)
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
typedef map<char,int> MAP;
void print(MAP::value_type t)
{
 cout<<t.first<<": 有"<<t.second<<"个"<<endl;
}
void CountCharacter(MAP &m,char *szText)
{
 char *p=szText;
 if (!p)
  return;
 while (*p)
 {
  MAP::iterator it=NULL;
  it=m.find(*p);
  if (it==m.end())
  {
   m.insert(MAP::value_type(*p,1));
  }
  else
  {
   ++(it->second);
  }
  ++p;
 }
 return;
}
int main()
{
 MAP myMap;
 char szText[512]={0};
 cout<<"请输入一字符串:"<<endl;
 fgets(szText,512,stdin);
 szText[strlen(szText)-1]=0;
 CountCharacter(myMap,szText);
 for_each(myMap.begin(),myMap.end(),print);
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值