When I want to convert NSString to int
I use:
[string intValue];
But how to determine if string is int value? for instance to avoid situations like this:
[@"hhhuuukkk" intValue];
int value;
NSString *s = @"huuuk";
if([[NSScanner scannerWithString:s] scanInt:&value]) {
//Is int value
}
else {
//Is not int value
}
Edit: added isAtEnd check according to Martin R's suggestion. This will make sure it is only digits in the whole string.
int value;
NSString *s = @"huuuk";
NSScanner *scanner = [NSScanner scannerWithString:s];
if([scanner scanInt:&value] && [scanner isAtEnd]) {
//Is int value
}
else {
//Is not int value
}
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