NSString *test = @"example";
NSString *test2 = @"ex12am243ple";
是否有任何簡單的方法來確定哪個字符串包含一個數字(0-9),哪一個不是?我的一些NSString是字母數字。我如何判斷哪些包含數字,哪些不包含數字?
謝謝。
NSString *test = @"example";
NSString *test2 = @"ex12am243ple";
是否有任何簡單的方法來確定哪個字符串包含一個數字(0-9),哪一個不是?我的一些NSString是字母數字。我如何判斷哪些包含數字,哪些不包含數字?
謝謝。
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」。
if ([test isMatchedByRegEx:@"\d+"]) {
// string contains numbers
}
編輯:還值得一提的是,你需要導入regex.h
你可以使用正則表達式來測試數字。以下是一個示例,但您可能需要根據需要進行更改。
- (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;
}
只要添加到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
您應該添加如何獲得characterSet ...雖然很好的答案! –
yea在下面添加了它。猜我可以改變實際的代碼塊.. –