Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a better way to check if a string is an integer on iPhone?

The following code will identify if a string is an integer - that is, the string contains only digits. But, I hate this code. What is a better way?

NSString *mightBeAnInteger = fooString;
int intValue = [fooString intValue];
if (intValue > 0
    && [[NSString stringWithFormat:@"%d",intValue] isEqualToString:mightBeAnInteger]) {
  NSLog(@"mightBeAnInteger is an integer");
}
like image 651
Andrew Johnson Avatar asked Feb 01 '11 03:02

Andrew Johnson


People also ask

How do you check if a string is an integer or int?

We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.

How do you check if something is an integer or not?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

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

A simple approach to check if a Python string contains a number is to verify every character in the string using the string isdigit() method. Once that's done we get a list of booleans and if any of its elements is True that means the string contains at least one number.


1 Answers

[fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound will be YES if the string only has number characters in it.

Note that this doesn't catch negative numbers, so you'll have to add in the negative sign (probably by grabbing a mutableCopy and adding the sign).

like image 115
kevboh Avatar answered Oct 18 '22 00:10

kevboh