2011-09-28 83 views

回答

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」。

+0

您應該添加如何獲得characterSet ...雖然很好的答案! –

+0

yea在下面添加了它。猜我可以改變實際的代碼塊.. –

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

編輯:還值得一提的是,你需要導入regex.h

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; 
} 
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 
相關問題