2

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];
iPatel
  • 46,010
  • 16
  • 115
  • 137
Paul T.
  • 4,938
  • 7
  • 45
  • 93

5 Answers5

7
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
}
www.jensolsson.se
  • 3,023
  • 2
  • 35
  • 65
2

The C way: use strtol() and check errno:

errno = 0;
int n = strtol(str.UTF8String, NULL, 0);
if (errno != 0) {
    perror("strtol");
    // or handle error otherwise
}

The Cocoa way: use NSNumberFormatter:

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setGeneratesDecimalNumbers:NO];
NSNumber *num = nil;
NSError *err = nil;
NSRange r = NSMakeRange(0, str.length);

[fmt getObjectValue:&num forString:str range:&r error:&err];
if (err != nil) {
    // handle error
} else {
    int n = [num intValue];
}
0
 NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
 [f setNumberStyle:NSNumberFormatterDecimalStyle];
 NSNumber * amt = [f numberFromString:@"STRING"];

 if(amt)
 { 
        // convert to int if you want to like you have done in your que.

       //valid amount
 }
 else
 {
     // not valid
 }
keen
  • 3,001
  • 4
  • 34
  • 59
0
NSString *yourStr = @"hhhuuukkk";
NSString *regx = @"(-){0,1}(([0-9]+)(.)){0,1}([0-9]+)";
NSPredicate *chekNumeric = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regx];
BOOL isNumber = [chekNumeric evaluateWithObject:yourStr];

if(isNumber)
{
  // Your String has only numeric value convert it to intger;
}
else
{
  // Your String has NOT only numeric value also others;
}

For only integer value change Rgex pattern to ^(0|[1-9][0-9]*)$ ;

iPatel
  • 46,010
  • 16
  • 115
  • 137
0
NSString *stringValue = @"hhhuuukkk";
if ([[NSScanner scannerWithString:stringValue] scanInt:nil]) {
    //Is int value
}
else{
    //Is not int value
}

[[NSScanner scannerWithString:stringValue] scanInt:nil] will check if "stringValue" has an integer value.

It returns a BOOL indicating whether or not it found a suitable int value.

thatzprem
  • 4,697
  • 1
  • 33
  • 41