开发者

Some of my NSStrings are alphanumeric. How do I tell which ones contain numbers and which ones don't?

NSString *test = @"example";

NSString *test2 = @"ex12am243ple";

Is there any easy way to determi开发者_运维百科ne which string contains a number in it (0-9) and which one doesn't?

Thanks.


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. you can look at the docs of NSCharacterSet for the available ones, but the one you probably want is decimalDigitCharacterSet so you would use [NSCharacterSet decimalDigitCharacterSet] in place of "characterSetOfNumbers" in the above code.


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

EDIT: also worth noting that you need to import regex.h


Just to add to Jesse's code, it is definitely easier to put it into a category.

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

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


You could use a regular expression to test for numbers. Here is an example but you may need to change it for your needs.

- (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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜