Check If A String Contains Only Letters In C++
Code snippet for how to Check If A String Contains Only Letters In C++ with sample and detail explanation
In this article, we will be exploring the process of checking if a string in C++ contains only letters. This is often a useful task when dealing with user input validation, compiler design, and a variety of other programming tasks.
Code snippet for Checking if a String Contains Only Letters
#include <cctype>
#include <string>
bool checkString(const std::string& str) {
for(char const &c : str) {
if(!std::isalpha(c))
return false;
}
return true;
}
You can test this function with following code snippet:
int main() {
std::string test1 = "HelloWorld";
std::string test2 = "Hello World!";
bool res1 = checkString(test1);
bool res2 = checkString(test2);
std::cout<< "test1: " << (res1 ? "Contains only letters" : "Contains other characters") << std::endl;
std::cout<< "test2: " << (res2 ? "Contains only letters" : "Contains other characters") << std::endl;
return 0;
}
Code Explanation for Checking if a String Contains Only Letters
Let’s break down how this code snippet works, step by step.
-
We start by including the necessary libraries:
<cctype>
and<string>
. The<cctype>
library provides us with thestd::isalpha()
function, which checks if a particular character is a letter. -
We define a function
checkString
which takes a constant string reference as its argument. -
Inside this function, we loop through each character in the string.
-
For each character, we use the
std::isalpha()
function to check if it is a letter. Ifstd::isalpha(c)
encounters a character which isn’t a letter, it returnsfalse
and we immediately returnfalse
from ourcheckString
function. -
If our function has checked each character and not found any non-letter characters, it returns
true
, signifying that the string does indeed only contain letters.
In the test code, the string “HelloWorld” contains only letters, so checkString(test1)
will return true. On the other hand, the string “Hello World!” contains a space and an exclamation mark, along with letters. Thus, checkString(test2)
will return false.