Home > Article > Backend Development > How to Determine if a String or Character Array Contains Only Digits in C ?
Determining Numericity of Strings and Character Arrays
In C , verifying if a string or character array (char*) comprises exclusively numeric characters is a common requirement. Let's explore two reliable methods:
Method 1: find_first_not_of()
This method utilizes the find_first_not_of() function, which seeks the first occurrence of a non-digit character. If no such character is found, it returns std::string::npos, signifying the presence of only digits:
<code class="cpp">bool is_digits(const std::string &str) { return str.find_first_not_of("0123456789") == std::string::npos; }</code>
Method 2: std::all_of()
This method leverages the std::all_of() function, which checks if all elements in a range satisfy a given predicate. In this case, the predicate is ::isdigit, which returns true for numeric characters:
<code class="cpp">bool is_digits(const std::string &str) { return std::all_of(str.begin(), str.end(), ::isdigit); // C++11 }</code>
Comparison for Strings and Character Arrays
Both methods are equally applicable to both strings and character arrays. However, character arrays require explicit conversion to strings before utilizing the std::string member functions.
The above is the detailed content of How to Determine if a String or Character Array Contains Only Digits in C ?. For more information, please follow other related articles on the PHP Chinese website!