64,691
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n=0,sum=0;
string s1("qwertyqwertyqwerty");
string s2("ert");
string temp=s1;
while (1)
{ //循环:查找到子串就把子串删去
n=temp.find(s2); //返回子串的位置
if (n!=-1)
{ //n=-1表示未找到子串
temp=temp.substr(n+s2.length(),temp.length()-s2.length()); //开一个新的字符串变量temp存储删去子串后的字符串
sum++; //出现次数
}
else break;
}
cout<<sum;
}
int main()
{
int sum=0;
string s1("qwertyqwertyqwerty");
string s2("ert");
const int maxlen=32; // 设置到足够长
int arr[maxlen];
int pos=s1.find(s2);
while (pos!=-1)
{
arr[sum++]=pos;
pos=s1.find(s2,pos+1);
}
cout <<"sum:\t" <<sum <<endl <<endl;;
for(int i=0;i<sum;++i)
cout <<"[" <<i <<"]:\t" <<arr[i] <<endl;
return 0;
}