OneBite.Dev - Coding blog in a bite size

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.

  1. We start by including the necessary libraries: <cctype> and <string>. The <cctype> library provides us with the std::isalpha() function, which checks if a particular character is a letter.

  2. We define a function checkString which takes a constant string reference as its argument.

  3. Inside this function, we loop through each character in the string.

  4. For each character, we use the std::isalpha() function to check if it is a letter. If std::isalpha(c) encounters a character which isn’t a letter, it returns false and we immediately return false from our checkString function.

  5. 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.

c-plus-plus