Replace multiple char actors in a string with a single char

What is the best way to replace multiple characters in a string with a single char?

string str("1 1 1"); //out: 1 1 1 
+4
source share
1 answer
 str.erase( std::unique(str.begin(), str.end()), str.end()); 

This will work not only in spaces. For example, the string "aaabbbcccddd" will become "abcd". Is this what you want? If you just want to reduce the spaces to one place, you can pass the binary predicate as the third argument to std::unique , like this one:

 bool BothAreSpaces(char lhs, char rhs) { return (lhs == ' ') && (rhs == ' '); } 
+8
source

Source: https://habr.com/ru/post/1387885/


All Articles