Home > Article > Backend Development > How Can You Check for Digits in C Strings and Char Pointers?
Checking for Digits in C Strings and Char Pointers
Determining whether a string or character pointer contains only numeric characters is a common task in programming. C provides several ways to perform this check, applicable to both std::string and char*.
String-Based Method
To check if a std::string contains only digits, you can use the find_first_not_of() function. This function returns the position of the first character that does not match the specified set of characters. If the function returns std::string::npos, it indicates that no non-digit character was found, and hence the string contains only digits.
<code class="cpp">bool is_digits(const std::string &str) { return str.find_first_not_of("0123456789") == std::string::npos; }</code>
Char Pointer-Based Method
For a character pointer, you can use the std::all_of() function along with the ::isdigit function to check if all characters in the pointer are digits. The ::isdigit function returns true if the character is a digit (0-9), and false otherwise.
<code class="cpp">bool is_digits(const char* str) { return std::all_of(str, str + strlen(str), ::isdigit); // C++11 }</code>
Note that both methods assume that the input string or character pointer is a sequence of ASCII characters. If non-ASCII characters are expected, appropriate modifications may be necessary.
The above is the detailed content of How Can You Check for Digits in C Strings and Char Pointers?. For more information, please follow other related articles on the PHP Chinese website!