Home > Backend Development > C++ > How Can You Check for Digits in C Strings and Char Pointers?

How Can You Check for Digits in C Strings and Char Pointers?

Susan Sarandon
Release: 2024-11-02 17:17:02
Original
217 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template