user3105379
user3105379

Reputation:

Removing consecutive duplicate characters from a std::string

I'm currently trying to remove duplicate characters. For example:

I have written the following piece of code:

string.erase(remove(string.find_first_of(string[i]) + 1, string.end(), string[i]), string.end());

but apparently std::string returns a pointer to the last + 1 character of the string, rather than the size, any ideas how I could remove string[i] from my string starting from the position next to that char?

Upvotes: 0

Views: 639

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

string.find_first_of returns an integer position (and string::npos if not found). This is not compatible withstd::remove, which expects iterators. You can convert from a position to an iterator by adding the position to the begin iterator.

char to_remove = string[i];
auto beg = string.begin() + string.find_first_of(to_remove) + 1;
auto new_end = std::remove(beg, string.end(), to_remove); 
string.erase(new_end, string.end());

Upvotes: 1

Related Questions