c++中一个子字符串在另一个字符串中出现的次数
1个回答
展开全部
#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;
}
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询