c++ - Remove duplicates in string algorithm -
my homework remove duplicates in random string. idea use 2 loops solve problem.
1st 1 scan every character in string. 2nd 1 check character duplicated or not. if so, remove character.
string content = "blah blah..." (int = 0; < content.size(); ++i) { char check = content.at(i); (int j = + 1; j < content.size() - 1; ++j) { if (check == content.at(j)) { content.erase(content.begin()+j); } } }
the problem doesn't work. removes wrong character. seems indices problem don't understand why.
a temporary fix change content.erase(content.begin()+j);
content.erase( remove(content.begin() + i+1, content.end(), check),content.end());
but think trigger "remove value" scan isn't nice way. want 2 loops or fewer.
any ideas appreciated :)
your loops following way
#include <iostream> #include <string> int main() { std::string s = "blah blah..."; std::cout << '\"' << s << '\"' << std::endl; ( std::string::size_type = 0; < s.size(); i++ ) { std::string::size_type j = + 1; while ( j < s.size() ) { if ( s[i] == s[j] ) { s.erase( j, 1 ); } else { ++j; } } } std::cout << '\"' << s << '\"' << std::endl; return 0; }
the output is
"blah blah..." "blah b."
there many other approaches using standard algorithms. example
#include <iostream> #include <string> #include <algorithm> #include <iterator> int main() { std::string s = "blah blah..."; std::cout << '\"' << s << '\"' << std::endl; auto last = s.end(); ( auto first = s.begin(); first != last; ++first ) { last = std::remove( std::next( first ), last, *first ); } s.erase( last, s.end() ); std::cout << '\"' << s << '\"' << std::endl; return 0; }
the output same previous code example
"blah blah..." "blah b."
Comments
Post a Comment