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

1. Using string::find_first_not_of

We can use the string::find_first_not_of function to check the absence of a character in the string. It returns string::npos if the string does not contain any of the specified characters. To check if a string contains only letters, do as follows:

Download  Run Code

2. Using string::find_if

The std::find_if algorithm returns an iterator to the first element in the specified range for which the specified predicate returns true. If the predicate returns false for all elements, the function returns an iterator to the end of the specified range. We can use a combination of std::find_if and std::isalpha to match for all alphabetic characters, as shown below:

Download  Run Code

 
We can further shorten the code using adaptors from the <functional> header:

Download  Run Code

3. Using std::all_of

The std::all_of function returns true if all of the elements of the supplied range are true according to a predicate function. It is available since C++11 and can be used as follows to check if a string contains only alphabets.

Download  Run Code

4. Using std::regex_match

Finally, we can use a regular expression to check whether a string contains only letters. Starting with C++11, we can use std::regex_match to match a sequence against a regular expression.

Download  Run Code

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