This post will discuss how to remove all non-alphanumeric characters from a string in C++. Non-alphanumeric characters are those that are not letters (A-Z, a-z) or numbers (0-9).

We may want to remove all non-alphanumeric characters from a string to sanitize user input, to normalize text for comparison, or to perform some other transformation. There are several ways to do it in C++:

1. Using std::remove_if algorithm

A simple solution to remove all non-alphanumeric characters from a string is to use the std::remove_if algorithm and the std::isalnum function. The std::remove_if algorithm allows us to remove elements from a sequence that satisfy a given predicate. The predicate is a function or a functor that takes an element as an argument and returns true if it should be removed or false if it should be kept. The std::isalnum function can be used as a predicate to check if a character is alphanumeric or not.

To use this function, we need to pass the beginning and ending iterators of our string and the predicate to the std::remove_if algorithm. The std::remove_if algorithm returns an iterator that indicates where the end should be, which can be passed to the std::erase function. For example:

Download  Run Code

2. Using indexing operator

The simplest and most intuitive way to remove all non-alphanumeric characters from a string is to use the indexing operator [] and the std::isalnum function. The indexing operator allows us to access and modify any character in a string by its position, starting from zero. The std::isalnum function checks if a character is alphanumeric or not. It returns true if the character is a letter or a digit, and false otherwise.

To use this function, we need to loop through each character in the string and check if it is alphanumeric using the std::isalnum function. If it is not, we erase it using the string::erase function. For example:

Download  Run Code

3. Using Regular Expressions

The third option to create a regular expression object that matches all non-alphanumeric characters using the syntax [^a-zA-Z0-9]. The ^ symbol means negation, the a-z range means lowercase letters, the A-Z range means uppercase letters, and the 0-9 range means digits. Then, we can use the regex_replace() function to replace all matches of the regular expression with an empty string. To use this method, we need to include the standard library header <regex> that supports regular expressions. Here is an example of this approach:

Download  Run Code

4. Using std::erase_if algorithm

Starting with C++20, consider using the std::erase_if algorithm that is error-free wrapper over the erase-remove idiom. Here is an example of using this function:

Download Code

That’s all about removing all non-alphanumeric characters from a string in C++.