#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;
}
温馨提示:答案为网友推荐,仅供参考