Paul T.
Paul T.

Reputation: 5038

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];

Upvotes: 2

Views: 283

Answers (5)

thatzprem
thatzprem

Reputation: 4767

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.

Upvotes: 0

www.jensolsson.se
www.jensolsson.se

Reputation: 3083

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
}

Upvotes: 7

keen
keen

Reputation: 3011

 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
 }

Upvotes: 0

iPatel
iPatel

Reputation: 47119

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]*)$ ;

Upvotes: 0

user529758
user529758

Reputation:

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];
}

Upvotes: 2

Related Questions