Erase a part of a std::string multiple times

The problem occurs when all occurences of WUB are erased: if there is no WUB left in the string, find will return the magic value string::npos, which is usually a very large number and accessing this index will likely lead to an out of bounds exception.

See the documentation:

The position of the first character of the first match. If no matches
were found, the function returns string::npos.

Here is a working example in Ide-One, without the new line below it will throw:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::erase: __pos (which is 4294967295) > this->size() (which is 25)

Adding a check if the string contains the search string fixes the problem:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string x = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
    string s;
    for(int i=0; i<x.size(); i++)
    {
        if (x.find("WUB") != string::npos) // <=== this is new
            s = x.erase(x.find("WUB"),3);
    }
    cout<<s;
    return 0;
}

PS: I don’t think the question deserved 10 downvotes.

Leave a Comment