2

可能重复:
NSString 是整数?

我正在寻找一个字符串是否只有数字。基本上:

if (string is integer):
   #do whatever
else:
   #error

我该怎么做?谢谢!

4

2 回答 2

5

我用过[NSCharacterSet decimalDigitCharacterSet]。绝对运作良好。

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}
于 2012-09-02T20:02:17.557 回答
0
-(BOOL)isANumber:(NSString *)string{
    NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '^[0-9]+$'"];
    return [numberPredicate evaluateWithObject:string];
}
于 2012-09-02T20:02:20.973 回答