Home >Backend Development >C++ >How Can I Verify if a String or char* Contains Only Digits in C ?

How Can I Verify if a String or char* Contains Only Digits in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 04:18:30791browse

How Can I Verify if a String or char* Contains Only Digits in C  ?

Checking for Digit-Only Strings in C

Determining whether a string or char* contains only digits is a common task in programming. This article explores two efficient approaches:

1. Using find_first_not_of

This method iterates through the string, searching for the first non-digit character. If none is found (find_first_not_of("0123456789") returns std::string::npos), the string is considered digit-only:

<code class="cpp">bool is_digits(const std::string &amp;str)
{
    return str.find_first_not_of("0123456789") == std::string::npos;
}</code>

2. Using std::all_of (C 11 onwards)

This method utilizes a predicate to check each character of the string. In this case, the predicate is ::isdigit, which returns true for digit characters:

<code class="cpp">bool is_digits(const std::string &amp;str)
{
    return std::all_of(str.begin(), str.end(), ::isdigit); // C++11
}</code>

Do the Functions Apply to Both Strings and char*?

Yes, these functions can be used for both std::string and char* with minor modifications. For char*, the std::string constructor can be used to convert the char* to a std::string:

<code class="cpp">bool is_digits(const char *str)
{
    std::string str_copy(str);
    return is_digits(str_copy);
}</code>

The above is the detailed content of How Can I Verify if a String or char* Contains Only Digits in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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