2

当我想转换NSStringint
我使用:

[string intValue];

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

[@"hhhuuukkk" intValue];
4

5 回答 5

7
int value;
NSString *s = @"huuuk";
if([[NSScanner scannerWithString:s] scanInt:&value]) {
    //Is int value
}
else {
    //Is not int value
}

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

int value;
NSString *s = @"huuuk";
NSScanner *scanner = [NSScanner scannerWithString:s];
if([scanner scanInt:&value] && [scanner isAtEnd]) {
    //Is int value
}
else {
    //Is not int value
}
于 2013-09-07T09:09:47.443 回答
2

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

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

可可方式:使用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];
}
于 2013-09-07T09:11:14.880 回答
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
 }
于 2013-09-07T09:08:06.777 回答
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;
}

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

于 2013-09-07T09:08:17.390 回答
0
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 值。

于 2013-09-07T09:14:59.787 回答