我的一些NSStrings是字母数字。如何判断哪些包含数字而哪些包含数字?

时间:2011-09-28 22:15:44

标签: iphone cocoa-touch cocoa ipad

NSString *test = @"example";

NSString *test2 = @"ex12am243ple";

有没有简单的方法可以确定哪个字符串包含一个数字(0-9),哪一个不包含?

感谢。

4 个答案:

答案 0 :(得分:6)

if([testString rangeOfCharacterFromSet:characterSetOfNumbers].location == NSNotFound)
{
//there are no numbers in this string
}
else
{
//there is at least 1 number in this string
}

P.S。您可以查看NSCharacterSet的可用文档,但您可能想要的文档是decimalDigitCharacterSet,因此您可以在上面的代码中使用[NSCharacterSet decimalDigitCharacterSet]代替“characterSetOfNumbers”。 / p>

答案 1 :(得分:1)

if ([test isMatchedByRegEx:@"\d+"]) {
   // string contains numbers
}

编辑:还值得注意的是,您需要导入regex.h

答案 2 :(得分:1)

只是添加到Jesse的代码中,将它放入类别中肯定更容易。

@interface NSString (Numeric)
- (BOOL) isNumeric;
@end

@implementation NSString (numeric)
- (BOOL) isNumeric {
    NSCharacterSet *numbers = [NSCharacterSet decimalDigitCharacterSet];
    return ([self rangeOfCharactersFromSet:numbers].location == NSNotFound ? YES : NO);
}
@end 

答案 3 :(得分:0)

您可以使用正则表达式来测试数字。这是一个示例,但您可能需要根据需要进行更改。

- (BOOL)stringContainsNumbers:(NSString *)string {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:0 error:NULL];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
    return  numberOfMatches > 0;
}