OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In C++

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In C++ with sample and detail explanation

Inspecting a string to check if it contains only alphanumeric characters within a C++ program is a common requirement in the software development domain. This article will walk you through the steps of handling such a task using a simple example in C++.

Code snippet: Checking for Alphanumeric Characters in a String

#include<iostream>
#include<algorithm>

bool isAlphanumeric(const std::string str){
   return std::all_of(str.begin(), str.end(), ::isalnum);
}

int main()
{
   std::string str;
   std::cout << "Enter a string: ";
   std::getline(std::cin, str);

   if(isAlphanumeric(str))
      std::cout << "The string consists of only alphanumeric characters.\n";
   else
      std::cout << "The string contains non-alphanumeric characters.\n";

   return 0;
}

Code Explanation: Checking for Alphanumeric Characters in a String

The purpose of this program is to check whether a given string input by the user includes only alphanumeric characters or not.

In the heading of the code, we begin by including the necessary libraries, namely <iostream> for input/output operations and <algorithm> that provides us access to various algorithmic operations including std::all_of().

The function bool isAlphanumeric(const std::string str) is defined to perform the main task of checking the alphanumeric property of the input string. The standard algorithm std::all_of() is used inside this function which tests whether all elements in the range (in this case, the range is from the beginning to the end of the string) satisfy a certain predicate. The predicate used here is ::isalnum, which checks if a character is alphanumeric.

This function will return true if all characters in the input string are alphanumeric else it will return false.

In the main() function, we first prompt the user to enter a string.

Once the string is input, the function isAlphanumeric(str) is called with the input string as its argument.

Once the result from the function is available, the program will print on the console whether the string just consists of alphanumeric characters or if it includes non-alphanumeric ones too. The message is displayed using std::cout.

This program can easily be extended or adjusted according to individual requirements, to provide more complex string analysis functions.

c-plus-plus