查找string中同一个字符的位置问题

martinfa 2011-12-13 01:37:25
#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;

}




以上我只实现了找到同一个字符串出现几次,但我还想知道一个字符串出现第几次的位置,该如何修改呢?
...全文
108 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
追求执着 2011-12-13
  • 打赏
  • 举报
回复
find_first_of()或者find()
yisikaipu 2011-12-13
  • 打赏
  • 举报
回复
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;
}
pengzhixi 2011-12-13
  • 打赏
  • 举报
回复
用find_first_of循环查找,保存返回的值就是了。

64,691

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧