Home > Backend Development > C++ > body text

How to Determine if a String or Character Array Contains Only Digits in C ?

Susan Sarandon
Release: 2024-11-02 17:21:03
Original
218 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!