想用一个循环遍历string,大伙看看这是为什么。
想用一个循环遍历string,大家看看这是为什么。。
教教我为什么,谢谢了
------解决方案--------------------
while(beg!=s.end() && *beg==' '){//为什么执行完这两个循环的时候已经到end了??????
++beg;
}
迭代器已经指向尾部了,下面的循环就不能运行了呀
while(beg!=s.end() && *beg!=' '){
stemp+=*beg;
++beg;
}
------解决方案--------------------
执行结果是正常的 "aaaa"
还有,用std::remove和std::remove_copy会更容易
------解决方案--------------------
1.你的代码要干啥?把非空格字符选出来放到stemp里边?可你的stemp没进行一次最外层循环就清空一次,所以你的stemp只能收集到最后一个非空字符。
2.内部的第一个循环没有必要再检查是否到尾部。
3.因为你最后cout的条件是循环到了尾部,所以肯定只会输出一次,因为只会到尾部一次。
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,也就是循环只执行了一次就到尾了,不应该啊
教教我为什么,谢谢了
------解决方案--------------------
while(beg!=s.end() && *beg==' '){//为什么执行完这两个循环的时候已经到end了??????
++beg;
}
迭代器已经指向尾部了,下面的循环就不能运行了呀
while(beg!=s.end() && *beg!=' '){
stemp+=*beg;
++beg;
}
------解决方案--------------------
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;
------解决方案--------------------
1.你的代码要干啥?把非空格字符选出来放到stemp里边?可你的stemp没进行一次最外层循环就清空一次,所以你的stemp只能收集到最后一个非空字符。
2.内部的第一个循环没有必要再检查是否到尾部。
3.因为你最后cout的条件是循环到了尾部,所以肯定只会输出一次,因为只会到尾部一次。