Replace Non-Alphanumeric Characters in a C++ String

I needed to replace the non-alphanumeric characters in a std::string. While the Java String class has the replace() and replaceAll() methods for doing this, the std::string class has no such utility methods. Instead you can use the std::replace_if function from the Standard Template Library. Here’s some example code:

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

int isNotAlphaNum(char c)
{
        return !std::isalnum(c);
}

int main(int argc, char* argv[])
{
        std::string s1 = "some/string/with*/nonalpha/characters+1";
        std::cout << s1 << " : ";
        std::replace_if(s1.begin(), s1.end(), isNotAlphaNum, ' ');
        std::cout << s1 << std::endl;
        return 0;
}

The third parameter of the replace_if() function is a pointer to a function that performs the desired check and returns either true or false if the input satisfies the condition. The last parameter is the character to replace the matched character, in this case a space. This program produces the following:

$ ./replace.exe
some/string/with*/nonalpha/characters+1
some string with  nonalpha characters 1

Related Posts

Leave a Reply