Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a character in a string is an integer

Let's say I want to look at the character at position 10 in a string s.

s.at(10);

What would be the easiest way to know if this is a number?

like image 449
neuromancer Avatar asked Feb 26 '10 09:02

neuromancer


People also ask

How do you check if an element in a string is an integer?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

How do you check if a character in a string is an integer Python?

To check if a string is an integer or a float:Use the str. isdigit() method to check if every character in the string is a digit. If the method returns True , the string is an integer.

How do I check if a string is integer or float?

If the float number only has '. 0' after it then it converts it into a integer. while CorrectNumber == False: try: Number = float(NumberString) - 0 print (Number) except: print ("Error! Not a number!")


4 Answers

Use isdigit

std::string s("mystring is the best");
if ( isdigit(s.at(10)) ){
    //the char at position 10 is a digit
}

You will need

#include <ctype.h>

to ensure isdigit is available regardless of implementation of the standard library.

like image 52
Yacoby Avatar answered Oct 05 '22 06:10

Yacoby


The other answers assume you only care about the following characters: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. If you are writing software that might operate on locales that use other numeral systems, then you'll want to use the newer std::isdigit located in <locale>: http://www.cplusplus.com/reference/std/locale/isdigit/

Then you could recognize the following digits as digits: ४, ੬, ൦, ௫, ๓, ໒

like image 39
Bill Avatar answered Oct 05 '22 07:10

Bill


The following will tell you:

isdigit( s.at( 10 ) )

will resolve to 'true' if the character at position 10 is a digit.

You'll need to include < ctype >.

like image 21
Andrew Avatar answered Oct 05 '22 07:10

Andrew


Another way is to check the ASCII value of that character

if ( s.at(10) >= '0' && s.at(10) <= '9' )
  // it's a digit
like image 24
IVlad Avatar answered Oct 05 '22 08:10

IVlad