关于iphone:NSString到int问题

NSString to int issue

当我想将NSString转换为int
我用:

1
[string intValue];

但是如何确定字符串是否为int值? 例如,以避免这样的情况:

1
[@"hhhuuukkk" intValue];

1
2
3
4
5
6
7
8
int value;
NSString *s = @"huuuk";
if([[NSScanner scannerWithString:s] scanInt:&value]) {
    //Is int value
}
else {
    //Is not int value
}

编辑:根据Martin R的建议添加isAtEnd检查。 这将确保它只是整个字符串中的数字。

1
2
3
4
5
6
7
8
9
int value;
NSString *s = @"huuuk";
NSScanner *scanner = [NSScanner scannerWithString:s];
if([scanner scanInt:&value] && [scanner isAtEnd]) {
    //Is int value
}
else {
    //Is not int value
}


C方式:使用strtol()并检查errno

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

Cocoa方式:使用NSNumberFormatter

1
2
3
4
5
6
7
8
9
10
11
12
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];
}


1
2
3
4
5
6
7
NSString *stringValue = @"hhhuuukkk";
if ([[NSScanner scannerWithString:stringValue] scanInt:nil]) {
    //Is int value
}
else{
    //Is not int value
}

[[NSScanner scannerWithString:stringValue] scanInt:nil]将检查"stringValue"是否具有整数值。

它返回一个BOOL,指示它是否找到了合适的int值。


1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

仅对整数值将Rgex模式更改为^(0|[1-9][0-9]*)$;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
 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
 }