Deleting characters matching a pattern

C++:
Deleting characters matching a pattern

How to:

Let’s rip out characters using erase and remove_if alongside lambda expressions. Here’s a quick example:

#include <iostream>
#include <algorithm>
#include <string>

int main() {
    std::string data = "B4n4n4!";

    // Remove all numeric characters
    data.erase(std::remove_if(data.begin(), data.end(), ::isdigit), data.end());
    
    std::cout << data << std::endl; // Outputs: Bnn!
    
    return 0;
}

Sample output:

Bnn!

Deep Dive

The std::remove_if algorithm from <algorithm> header doesn’t actually shrink the string; it reorders elements and returns a pointer to the new logical end. The erase method of the std::string class then removes the “dead wood” from the end. This combo arrived with C++98 and remains efficient and popular.

Alternatives? For complex patterns, regex (<regex>) is your Swiss Army knife. But, it’s overkill for simple chores.

Details? std::remove_if and algorithms alike lean on iterators, which C++ adopted from the Standard Template Library (STL) in the mid-90s. They empower generic programming, ensuring your chop-and-change code works on strings, lists, you name it.

See Also