Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters in a string with one char

Tags:

c++

stl

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

string str("1   1     1");

//out: 1 1 1
like image 617
Alexander Abashkin Avatar asked Feb 22 '23 00:02

Alexander Abashkin


1 Answers

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 == ' ');
}
like image 191
Benjamin Lindley Avatar answered Mar 07 '23 21:03

Benjamin Lindley