daj
daj

Reputation: 7183

C++ erase / remove_if - only removes from the front of the string

Here str is a string:

str.erase(std::remove_if(str.begin(), str.end(), &islower));

only seems to remove lowercase characters from the front of the string. Why is that and how do I get it to remove all lowercase letters in the string?

Upvotes: 0

Views: 819

Answers (2)

Niall
Niall

Reputation: 30624

std::basic_string has two forms of erase taking iterators; the first for erasing a single character at that position and the second for a erasing the characters from a range.

  1. iterator erase(iterator position);
  2. iterator erase(iterator first, iterator last);

Try the two argument form:

str.erase(std::remove_if(str.begin(), str.end(), &islower), str.end());

It will erase the data in the range first to last, excluding last (thus [first; last)), from the position returned as the result of the remove_if to the end of the string.

This is commonly known as the erase-remove idiom.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

You're doing erase-remove wrong:

str.erase(std::remove_if(str.begin(), str.end(), &islower), str.end());
//                                                        ^^^^^^^^^^^

Your way uses the single-argument overload of std::string::erase that erases a single character, not the range overload that erases, well, a range.

Read the documentation!

Upvotes: 2

Related Questions