Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with remove_if (it stops removing after a few removals)

The code below wants to take a string and output only lowercase letters from the English alphabet.

string simplifyString(string word)
{
    word.erase(remove_if(word.begin(), word.end(), [](char letter){return !isalpha(letter);}));
    transform(word.begin(), word.end(), word.begin(), tolower);
    return word;
}

int main()
{
    string s = "a.b.c.d.e.f.g.h.";
    cout << simplifyString(s) << endl;;
    return 0;
}

The output is: abcdefgh.f.g.h.

So the code works and then stops working. What the heck is going on?

like image 987
user904963 Avatar asked Dec 21 '22 22:12

user904963


1 Answers

word.erase(remove_if(...));

That's close but not quite right. That only removes the first element set aside by remove_if. You want to remove the entire range:

word.erase(remove_if(...), word.end());
like image 199
Mooing Duck Avatar answered Dec 24 '22 01:12

Mooing Duck