64,647
社区成员
发帖
与我相关
我的任务
分享
string s=“a a a a”;
auto beg=s.begin();
while(beg!=s.end()){
stemp.clear();
while(beg!=s.end() && *beg==' '){//为什么执行完这两个循环的时候已经到end了??????
++beg;
}
while(beg!=s.end() && *beg!=' '){
stemp+=*beg;
++beg;
}
if(beg==s.end()){cout<<"x";}//这里是为了检验才写的,结果中只输出了一次x,也就是循环只执行了一次就到尾了,不应该啊
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
string smax,scurmax,stemp;
int max=0,curmax=0;
cin>>s;
auto beg=s.begin();
while(beg!=s.end()){
stemp.clear();
while(beg!=s.end() && *beg==' '){//为什么执行完这两个循环的时候已经到end了??????
++beg;
}
while(beg!=s.end() && *beg!=' '){
stemp+=*beg;
++beg;
}
if(beg==s.end()){cout<<"x";}
cout<<stemp<<endl;
if(stemp==scurmax){
++curmax;
}
else
{
scurmax=stemp;
curmax=1;
}
if(curmax>max){
max=curmax;
smax=scurmax;
//cout<<smax<<" "<<max<<endl;
}
}
cout<<"the word "<<smax<<" occurred "<<max<<" times"<<endl;
return 0;
}
std::string s= "a a a a";
std::string stemp;
auto beg = s.begin();
while(beg != s.end()){
//stemp.clear();
while(beg !=s.end() && *beg==' '){//为什么执行完这两个循环的时候已经到end了??????
++beg;
}
while(beg!=s.end() && *beg!=' '){
stemp+=*beg;
++beg;
}
}
std::cout<<stemp<<std::endl;
执行结果是正常的 "aaaa"
还有,用std::remove和std::remove_copy会更容易
std::string s = "a a a a";
std::string stemp;
std::remove_copy(std::begin(s), std::end(s), std::back_inserter(stemp), ' ');
std::cout<<stemp<<std::endl;
s.erase((std::remove(std::begin(s), std::end(s), ' ')), std::end(s));
std::cout<<s<<std::endl;