This tutorial will discuss about unique ways to check if a string contains only digits in C++.
Technique 1: Using STL Algorithm std::all_of()
To check if string has only digits we can use the STL algorithm all_of()
. t accepts three arguments,
- Iterator pointing to the first character of string.
- Iterator pointing to the end of string.
- A function ::isdigit(). It accepts a single character as an argument and returns true if the character is a digit.
The all_of()
function will apply the ::isdigit()
function on all the characters in string. If all the return values are true
then they all_of()
function will return true
, otherwise it will return false
.
If all_of()
function return false
, then it means there is atleast a character in the string that is not a digit. Whereas, if all_of()
function returns true
then it means all the characters in the string are digits.
Let’s see the complete example,
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "12345"; // Check if string has only digits bool allDigits = std::all_of( str.begin(), str.end(), ::isdigit); if (allDigits) { std::cout << "Yes, string contains all digits only." << std::endl; } else { std::cout << "No, string does not contains only digits." << std::endl; } return 0; }
Output :
Yes, string contains all digits only.
Technique 2: Using Regex
We can use the std::regex_match()
function, to check if a given string matches a regular pattern or not. To check if string contains only digits, we can use the regex pattern "\\d+"
. If the regex_match()
function returns true, for this regex pattern and a string, then it means that all characters in that string are digits.
Let’s see the complete example,
#include <iostream> #include <string> #include <regex> int main() { std::string str = "12345"; // Check if string has only digits bool allDigits = std::regex_match(str, std::regex("\\d+")); if (allDigits) { std::cout << "Yes, string contains all digits only." << std::endl; } else { std::cout << "No, string does not contains only digits." << std::endl; } return 0; }
Output :
Yes, string contains all digits only.
Summary
Today we learned about several ways to check if a string contains only digits in C++. Thanks.