Search code examples
c++stringreplaceall

A C++ way to replace all periods in a string with a single line of code?


A given string needs to be modified so that there are no periods. The rest of the string remains intact.

I thought of using an iterative approach and using string::erase. In java, I could have easily accomplished it with replaceAll function. Thinking along those lines a developer published a solution :

        temp.erase(remove(temp.begin(),temp.end(),'.'),temp.end());

The line of code works perfectly. However I failed to understand how it works. As far as my understanding goes the erase function deletes all characters in a range. The remove function is returning the iterator to the point after removing the periods, and then the erase function is erasing from that point. I'm confused. Any ideas?


Solution

  • It's easy to get confused but the remove function is not removing all the periods.

    Suppose before remove your string was "a.b.c." then after remove it would be "abc...". What the erase method is doing is erasing the periods that are now at the end of the string.

    Now it's a reasonable question to ask why remove behaves this way, but think about what remove has, it only has a pair of iterators. Iterators cannot be used to remove items from a container, an iterator does not give you access to the container that it refers to. So remove (and other similar functions) cannot delete anything from a container. All they can do is rearrange the order so that some later code can easily do the actual deleting.

    There's a name for this idiom but it escapes me at the moment.