当我想将NSString
转换为int
时
我用:
[string intValue];
但是如何判断字符串是否为int
值?例如,为了避免这样的情况:
[@"hhhuuukkk" intValue];
答案 0 :(得分: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
}
答案 1 :(得分:2)
C方式:使用strtol()
并检查errno
:
errno = 0;
int n = strtol(str.UTF8String, NULL, 0);
if (errno != 0) {
perror("strtol");
// or handle error otherwise
}
Cocoa方式:使用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];
}
答案 2 :(得分: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
}
答案 3 :(得分: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]*)$
;
答案 4 :(得分: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值。