Search code examples
c++stringwhile-loopcharerase

Why is deleting the space? c++ .erase()


I'm solving a kata in codewars, where you have to delete the exclamation mark '!'

But, when using .erase(), it deletes the space also. I'm not understanding how it deletes three '!' in a row.

This is the string that gives me problem:

"Hi! Hello!"

Debugging, it goes:

"HiHello!"

It ate the space and ends up as:

"HiHello"

This one works, but I don't understand when debugging it why doesn't appear more:

"Hello World!!!"

Goes to:

"Hello World"

I don't understand why it doesn't appear as "Hello World!!" and "Hello World!"

I used .erase() previously for splitting strings. I understood that .erase(first,second), where first is the start of the string inclusive and second is the end exclusive, also .erase() is a member function of std::string.

--Bonus-- I tried using .erase(pos,pos) and works equally.

Here is my code:

#include <string>

std::string removeExclamationMarks(std::string str){
    std::string remove{ "!" };
    std::cerr << str << '\n';
    size_t pos{};
    while( (pos = str.find(remove)) != std::string::npos ){
        std::cerr << pos << '\n';
        str.erase(pos, pos + remove.length());
        std::cerr << str << '\n';
    }
    std::cerr << "END\n";
    return str;
}

Solution

  • This call of the method erase is incorrect

    str.erase(pos, pos + remove.length());
    

    The second argument specifies the number of elements to be erased.

    So you need to write instead

    str.erase(pos, remove.length());
    

    Pay attention to that if your compiler supports C++20 then you can write

    std::erase( str, '!' );