objective-c 如何检查 NSString 是否为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2020360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:42:42  来源:igfitidea点击:

How to check if NSString is numeric or not

objective-cnsstring

提问by jaleel

Possible Duplicate:
iphone how to check that a string is numeric only

可能的重复:
iphone 如何检查字符串是否仅为数字

I have one NSString, then i want check the string is number or not.

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

I mean

我的意思是

NSString *val = @"5555" ;

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

How can I do this in Objective C?

我怎样才能在目标 C 中做到这一点?

回答by Dewayne Christensen

Use [NSNumberFormatter numberFromString: s]. It returns nil if the specified string is non-numeric. You can configure the NSNumberFormatter to define "numeric" for your particular scenario.

使用[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];
}

回答by outis

You could use rangeOfCharacterFromSet::

你可以使用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