haruhi
haruhi

Reputation: 197

Delete all characters in a string that are not alphabetic in C++

I have a string a, banana I want to remove the space and comma from the string. My code:

for(auto it = s.begin(); it != s.end(); ++it)
   if(!isalpha(*it)) s.erase(it);

But what I'm getting is A banana. If i just try with A banana then I get Abanana. I don't know why it doesn't remove the space when there is a comma before that?

Upvotes: 0

Views: 393

Answers (2)

Nick
Nick

Reputation: 471

General best practice for iterating through an array and removing elements from it: Iterate backwards

for(auto it = s.end() - 1; it >= s.begin(); it--)
    if(!isalpha(*it) || *it == ' ')
        s.erase(it);

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409404

This seems like a job for std::remove_if:

auto new_end = std::remove_if(begin(s), end(s), [](char c)
{
    return !isalpha(c);
});

// remove_if returns the new end, we need to erase from that to the old end
// (see the "erase-remove" idiom, https://en.wikipedia.org/wiki/Erase–remove_idiom)
s.erase(new_end, end(s));

The problem with your current code is that erase modifies the string you're iterating over, and you simply skip (with it++) the next character in the string.

You need to use the iterator returned by erase as the next iterator to check:

for(auto it = s.begin(); it != s.end(); /* empty */)
{
    if(!isalpha(*it))
        it = s.erase(it);
    else
        ++it;
}

Upvotes: 5

Related Questions