如何检查NSString是否包含数值? [英] How to check if NSString is contains a numeric value?

查看:103
本文介绍了如何检查NSString是否包含数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从公式生成的字符串,但是我只想使用该字符串,只要它的所有字符都是数字,如果不是我想做不同的事情,例如显示错误信息。

I have a string that is being generate from a formula, however I only want to use the string as long as all of its characters are numeric, if not that I want to do something different for instance display an error message.

我一直在观察,但我发现很难找到任何符合我想做的事情。我看过NSScanner,但我不确定它是否检查整个字符串然后我不确定如何检查这些字符是否为数字

I have been having a look round but am finding it hard to find anything that works along the lines of what I am wanting to do. I have looked at NSScanner but I am not sure if its checking the whole string and then I am not actually sure how to check if these characters are numeric

- (void)isNumeric:(NSString *)code{

    NSScanner *ns = [NSScanner scannerWithString:code];
    if ( [ns scanFloat:NULL] ) //what can I use instead of NULL?
    {
        NSLog(@"INSIDE IF");
    }
    else {
    NSLog(@"OUTSIDE IF");
    }
}

因此,经过几个小时的搜索,我偶然发现了一个完全符合我要求的实现。

So after a few more hours searching I have stumbled across an implementation that dose exactly what I am looking for.

所以,如果你想检查它们是否是你的NSString中的任何字母数字字符,这可以在这里工作

so if you are looking to check if their are any alphanumeric characters in your NSString this works here

-(bool) isNumeric:(NSString*) hexText
{

    NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];

    NSNumber* number = [numberFormatter numberFromString:hexText];

    if (number != nil) {
        NSLog(@"%@ is numeric", hexText);
        //do some stuff here      
        return true;
    }

    NSLog(@"%@ is not numeric", hexText);
    //or do some more stuff here
    return false;
}

希望这会有所帮助。

推荐答案

这样的事情可行:

@interface NSString (usefull_stuff)
- (BOOL) isAllDigits;
@end

@implementation NSString (usefull_stuff)

- (BOOL) isAllDigits
{
    NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
    return r.location == NSNotFound && self.length > 0;
}

@end

然后就像这样使用它:

NSString* hasOtherStuff = @"234 other stuff";
NSString* digitsOnly = @"123345999996665003030303030";

BOOL b1 = [hasOtherStuff isAllDigits];
BOOL b2 = [digitsOnly isAllDigits];

您不必将此功能包装在这样的私有类别扩展中,但它肯定会使它很容易重用..

You don't have to wrap the functionality in a private category extension like this, but it sure makes it easy to reuse..

我比其他人更喜欢这个解决方案,因为它不会溢出一些通过NSScanner扫描的int / float - 数字位数可以几乎任何长度。

I like this solution better than the others since it wont ever overflow some int/float that is being scanned via NSScanner - the number of digits can be pretty much any length.

这篇关于如何检查NSString是否包含数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆