Home >Backend Development >C++ >How to Determine if a C String or char* Contains Only Digits?
How to Verify if a C String or char* Consists Exclusively of Digits
Question:
In C , is it possible to determine whether a given string or char* contains only numeric characters? If so, how do we find the first non-digit character, and do similar methods apply to both types?
Answer:
Yes, there are multiple techniques to assess if a string or char* consists solely of digits. Here are two potential approaches:
This method checks for the first occurrence of a non-digit character in the input. If the result is std::string::npos, it implies that all characters are digits.
<code class="cpp">bool is_digits(const std::string &str) { return str.find_first_not_of("0123456789") == std::string::npos; }</code>
This method uses the std::all_of algorithm to test if each character in the input meets a particular condition, in this case, whether it's a digit.
<code class="cpp">bool is_digits(const std::string &str) { return std::all_of(str.begin(), str.end(), ::isdigit); }</code>
Application to Both Types:
The methods discussed above can be utilized with both std::string and char types. However, it's crucial to ensure proper conversion or initialization when working with char to maintain consistency in data representation and prevent unintended behavior.
The above is the detailed content of How to Determine if a C String or char* Contains Only Digits?. For more information, please follow other related articles on the PHP Chinese website!