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");
}
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.
The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
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.
[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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With