c++中一个子字符串在另一个字符串中出现的次数

如题所述

#include <iostream>
using std::cout;
using std::endl;

//函数1: 查找子串sub在str中出现的次数--用C++方式--子串可重叠
int fun1(const std::string& str, const std::string& sub)
{
int num = 0;
for (size_t i=0; (i=str.find(sub,i)) != std::string::npos; num++, i++);
return num;
}

//函数2: 查找子串sub在str中出现的次数--用C方式--子串可重叠
int fun2(const char* str, const char* sub)
{
int num = 0;
for (const char* pstr=str; *pstr && (pstr=strstr(pstr,sub)); pstr++,num++);
return num;
}
//函数3: 查找子串sub在str中出现的次数--用C++方式--子串不重叠
int fun3(const std::string& str, const std::string& sub)
{
int num = 0;
size_t len = sub.length();
if (len == 0)len=1;//应付空子串调用
for (size_t i=0; (i=str.find(sub,i)) != std::string::npos; num++, i+=len);
return num;
}

//函数4: 查找子串sub在str中出现的次数--用C方式--子串不重叠
int fun4(const char* str, const char* sub)
{
int num = 0;
size_t len = strlen(sub);
if (len == 0)len=1;//应付空子串调用
for (const char* pstr=str; *pstr && (pstr=strstr(pstr,sub)); pstr+=len,num++);
return num;
}

void main()
{
std::string str("AAA");
std::string sub("AA");
cout<<fun1(str,sub)<<endl;
cout<<fun2(str.c_str(),sub.c_str())<<endl;
cout<<fun3(str,sub)<<endl;
cout<<fun4(str.c_str(),sub.c_str())<<endl;
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网