This post will discuss how to check if a string contains only alphanumeric characters in C++.

1. Using std::find_if

We can use the std::find_if standard algorithm from the <algorithm> header, which can accept a lambda to find the element in the specified range. It can be used as follows to check if a string contains only alphanumeric characters.

Download  Run Code

 
Since C++11, a better option is to use the std::find_if_not function. Its usage is demonstaed below:

Download  Run Code

 
We can further shorten the above code with isalnum from the global namespace which can be directly referenced with a name:

Download  Run Code

2. Using std::all_of

Since C++11, we can use the std::all_of function that returns true if the specified predicate holds for all the elements in the specified range. It can be used as follows to determine if the string contains only alphanumeric characters.

Download  Run Code

 
We can further shorten the above code with isalnum from the global namespace:

Download  Run Code

3. Using std::count_if

Finally, we can use the std::count_if algorithm to get the count of non-alphanumeric characters in the string. This approach would translate to the following code:

Download  Run Code

 
This is equivalent to:

Download  Run Code

That’s all about checking if a string contains only alphanumeric characters in C++.