Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to int issue

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];
like image 384
Paul T. Avatar asked Jul 12 '26 15:07

Paul T.


1 Answers

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
}
like image 80
www.jensolsson.se Avatar answered Jul 15 '26 05:07

www.jensolsson.se



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!