Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if given c++ string or char* contains only digits?

Or from the other way around find first non digit character.

Do the same functions apply for string and for char* ?

like image 279
rsk82 Avatar asked Jan 17 '12 01:01

rsk82


People also ask

How do you check if a string contains only digits in c?

You can use the isdigit() macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.

How can you check if string contains only digits?

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.

How do you check if a character in a string is a digit or letter C++?

The function isdigit() is used to check that character is a numeric character or not. This function is declared in “ctype. h” header file. It returns an integer value, if the argument is a digit otherwise, it returns zero.


1 Answers

Of course, there are many ways to test a string for only numeric characters. Two possible methods are:

bool is_digits(const std::string &str) {     return str.find_first_not_of("0123456789") == std::string::npos; } 

or

bool is_digits(const std::string &str) {     return std::all_of(str.begin(), str.end(), ::isdigit); // C++11 } 
like image 99
Blastfurnace Avatar answered Sep 21 '22 02:09

Blastfurnace