What the best way to replace multiple characters in a string with one char?
string str("1 1 1");
//out: 1 1 1
str.erase(
std::unique(str.begin(), str.end()),
str.end());
This will work on more than just the spaces though. For example, the string "aaabbbcccddd" would become "abcd". Is that what you want? If you just want to reduce the spaces to one space, you can pass a binary predicate as a third argument to std::unique
, like this one:
bool BothAreSpaces(char lhs, char rhs)
{
return (lhs == ' ') && (rhs == ' ');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With