问候, Larry 在这种情况下,我更喜欢以相反的顺序遍历容器。 在这种情况下,我们已经检查过的容器部分已经转移并且没有问题。 你不同意吗? I did this function:void clean(string&s){for(size_t i=0; i<s.size(); ++i){if(isalpha(s[i]))s[i]=tolower(s[i]);elses.erase(i,1);}return;}I''m having a strange behavior with string like these:"Disneyland" -> Disneyland".disneyland." -> .disneyland"It seems as if there is something going on with the erase function thati don''t know, because with this:void clean(string&s){string s2;for(size_t i=0; i<s.size(); ++i){if(isalpha(s[i])){s[i]=tolower(s[i]);s2+=s[i];}}s=s2;return;}Everything goes OK.What''s wrong with the first code?Thanks. 解决方案BenWell yes, erase() removes chars, so the size has changed.Here''s a quick and dirty example:#include <iostream>#include <string>#include <cctype>void clean( std::string& s ){std::string::iterator it;// step thru the string using the iterator ''it''for( it = s.begin(); it != s.end(); ){// if the current char is an alphaif( isalpha(*it) ){// change the char to lower case*it = tolower(*it);// increment ''it'' to the next char++it;}else{// delete the current non-alpha char from ''s''.// resets ''it'' to point to the first char after// the one just deleted - or to s.end() if no// more chars in ''s''.it = s.erase(it);}}return;}int main(){std::string t1 = "Disneyland";std::string t2 = ".disneyland.";clean(t1);clean(t2);std::cout << t1 << std::endl;std::cout << t2 << std::endl;return 0;}This program outputs:disneylanddisneylandRegards,Larry Well yes, erase() removes chars, so the size has changed. Here''s a quick and dirty example: #include <iostream> #include <string> #include <cctype> void clean( std::string& s ) { std::string::iterator it; // step thru the string using the iterator ''it'' for( it = s.begin(); it != s.end(); ) { // if the current char is an alpha if( isalpha(*it) ) { // change the char to lower case *it = tolower(*it); // increment ''it'' to the next char ++it; } else { // delete the current non-alpha char from ''s''. // resets ''it'' to point to the first char after // the one just deleted - or to s.end() if no // more chars in ''s''. it = s.erase(it); } } return; } int main() { std::string t1 = "Disneyland"; std::string t2 = ".disneyland."; clean(t1); clean(t2); std::cout << t1 << std::endl; std::cout << t2 << std::endl; return 0; } This program outputs: disneyland disneyland Regards, LarryIn cases like this, i prefer to traverse the container in reverse order.In that case the part of the container we have already examined isshifted and presents no problem.Wouldn''t you agree? 这篇关于字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 23:17