如何检查NSString是否为数字

时间:2010-01-07 12:52:42

标签: objective-c nsstring

  

可能重复:
  iphone how to check that a string is numeric only

我有一个NSString,然后我想检查字符串是否为数字。

我的意思是

NSString *val = @"5555" ;

if(val isNumber ){
  return true;
}else{
  retun false;
}

如何在Objective C中执行此操作?

2 个答案:

答案 0 :(得分:66)

使用[NSNumberFormatter numberFromString: s]。如果指定的字符串是非数字,则返回nil。您可以配置NSNumberFormatter为您的特定方案定义“数字”。


#import <Foundation/Foundation.h>

int
main(int argc, char* argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"];
    NSLocale *l_de = [[NSLocale alloc] initWithLocaleIdentifier: @"de_DE"];
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    [f setLocale: l_en];

    NSLog(@"returned: %@", [f numberFromString: @"1.234"]);

    [f setAllowsFloats: NO];
    NSLog(@"returned: %@", [f numberFromString: @"1.234"]);

    [f setAllowsFloats: YES];
    NSLog(@"returned: %@", [f numberFromString: @"1,234"]);

    [f setLocale: l_de];
    NSLog(@"returned: %@", [f numberFromString: @"1,234"]);

    [l_en release];
    [l_de release];
    [f release];
    [pool release];
}

答案 1 :(得分:8)

您可以使用rangeOfCharacterFromSet:

@interface NSString (isNumber)
-(BOOL)isInteger;
@end

@interface _IsNumber
+(void)initialize;
+(void)ensureInitialization;
@end

@implementation NSString (isNumber)
static NSCharacterSet* nonDigits;
-(BOOL)isInteger {
    /* bit of a hack to ensure nonDigits is initialized. Could also 
       make nonDigits a _IsNumber class variable, rather than an 
       NSString class variable.
     */
    [_IsNumber ensureInitialization];
    NSRange nond = [self rangeOfCharacterFromSet:nonDigits];
    if (NSNotFound == nond.location) {
        return YES;
    } else {
        return NO;
    }
}
@end

@implementation _IsNumber
+(void)initialize {
    NSLog(@"_IsNumber +initialize\n");
    nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
}
+(void)ensureInitialization {}
@end