Determine if a string begins with a number in C++
This post will discuss how to determine if a string begins with a number in C++.
1. Using isdigit() function
A simple solution is to extract the first character from the string, and check if it is numeric or not. This can be easily done using the isdigit() function, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <cctype> bool beginsWithNumber(std::string const &str) { if (str.length() == 0) { return false; } return isdigit(str[0]); } int main() { std::string str = "12ABC"; std::cout << std::boolalpha << beginsWithNumber(str) << std::endl; // true return 0; } |
Note the length check before accessing the first character from the string. The above code is roughly equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> bool beginsWithNumber(std::string const &str) { return str.length() > 0 && (str[0] >= '0' && str[0] <= '9'); } int main() { std::string str = "12ABC"; std::cout << std::boolalpha << beginsWithNumber(str) << std::endl; // true return 0; } |
2. Using Regex
Another option is to use a regular expression to determine whether a string begins with a number. Since C++11, we can use std::regex_match to match a sequence against a regex object. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <regex> bool beginsWithNumber(std::string const &str) { return std::regex_match(str, std::regex("^[0-9]+(.*)")); } int main() { std::string str = "12ABC"; std::cout << std::boolalpha << beginsWithNumber(str) << std::endl; // true return 0; } |
That’s all about determining if a string begins with a number in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)