ios 如何检查 NSString 是否包含数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6644004/
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-08-30 20:41:38  来源:igfitidea点击:

How to check if NSString is contains a numeric value?

iphoneiosnsstringnumeric

提问by C.Johns

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.

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

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

我一直在环顾四周,但发现很难找到任何符合我想做的事情的东西。我看过 NSScanner 但我不确定它是否检查整个字符串然后我实际上不确定如何检查这些字符是否是数字

- (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.

因此,经过几个小时的搜索,我偶然发现了一个实现,它正是我正在寻找的。

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

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

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

hope this helps.

希望这可以帮助。

回答by TomSwift

Something like this would work:

像这样的事情会起作用:

@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

then just use it like this:

然后像这样使用它:

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..

您不必像这样将功能包装在私有类别扩展中,但它确实可以轻松重用..

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.

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

回答by C.Johns

Consider NSString integerValue- it returns an NSInteger. However, it will accept some strings that are not entirely numeric and does not provide a mechanism to determine strings which are not numeric at all. This may or may not be acceptable.

考虑NSString integerValue- 它返回一个NSInteger. 但是,它会接受一些不完全是数字的字符串,并且不提供一种机制来确定根本不是数字的字符串。这可能会也可能不会被接受。

For instance, " 13 " -> 13, "42foo" -> 42and "helloworld" -> 0.

例如" 13 " -> 13"42foo" -> 42"helloworld" -> 0

Happy coding.

快乐编码。



Now, since the above was sort of a tangent to the question, see determine if string is numeric. Code taken from link, with comments added:

现在,由于上述内容与问题有关,请参阅确定 string 是否为 numeric。代码取自链接,并添加了注释:

BOOL isNumeric(NSString *s)
{
   NSScanner *sc = [NSScanner scannerWithString: s];
   // We can pass NULL because we don't actually need the value to test
   // for if the string is numeric. This is allowable.
   if ( [sc scanFloat:NULL] )
   {
      // Ensure nothing left in scanner so that "42foo" is not accepted.
      // ("42" would be consumed by scanFloat above leaving "foo".)
      return [sc isAtEnd];
   }
   // Couldn't even scan a float :(
   return NO;
}

The above works with just scanFloat-- e.g. no scanInt-- because the range of a float is much largerthan that of an integer (even a 64-bit integer).

以上仅适用于scanFloat- 例如没有scanInt- 因为浮点数的范围远大于整数(甚至是 64 位整数)的范围。

This function checks for "totally numeric" and will accept "42"and "0.13E2"but reject " 13 ", "42foo"and "helloworld".

此功能检查“完全数字”,将接受"42""0.13E2",但拒绝" 13 ""42foo""helloworld"

回答by arturdev

It's very simple.

这很简单。

+ (BOOL)isStringNumeric:(NSString *)text
{
    NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:text];        
    return [alphaNums isSupersetOfSet:inStringSet];
}

回答by Matt Connolly

Like this:

像这样:

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

    NSScanner *ns = [NSScanner scannerWithString:code];
    float the_value;
    if ( [ns scanFloat:&the_value] )
    {
        NSLog(@"INSIDE IF");
        // do something with `the_value` if you like
    }
    else {
    NSLog(@"OUTSIDE IF");
    }
}

回答by Alexander Larionov

Faced same problem in Swift.
In Swift you should use this code, according TomSwift's answer:

在 Swift 中遇到同样的问题。
根据 TomSwift 的回答,在 Swift 中您应该使用此代码:

func isAllDigits(str: String) -> Bool {

    let nonNumbers = NSCharacterSet.decimalDigitCharacterSet()

    if let range = str.rangeOfCharacterFromSet(nonNumbers) {
        return true
    }
    else {
        return false
    }
}

P.S. Also you can use other NSCharacterSets or their combinations to check your string!

PS 您也可以使用其他 NSCharacterSets 或它们的组合来检查您的字符串!

回答by Scott Yelvington

C.Johns' answer is wrong. If you use a formatter, you risk apple changing their codebase at some point and having the formatter spit out a partial result. Tom's answer is wrong too. If you use the rangeOfCharacterFromSet method and check for NSNotFound, it'll register a true if the string contains even one number. Similarly, other answers in this thread suggest using the Integer value method. That is also wrong because it will register a true if even one integer is present in the string. The OP asked for an answer that ensures the entirestring is numerical. Try this:

C.Johns 的回答是错误的。如果您使用格式化程序,您可能会冒着苹果在某些时候更改其代码库的风险,并使格式化程序吐出部分结果。汤姆的回答也是错误的。如果你使用 rangeOfCharacterFromSet 方法并检查 NSNotFound,如果字符串包含一个数字,它就会注册一个 true。同样,该线程中的其他答案建议使用整数值方法。这也是错误的,因为即使字符串中存在一个整数,它也会注册一个 true。OP 要求确保整个字符串都是数字的答案。尝试这个:

NSCharacterSet *searchSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

NSCharacterSet *searchSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

Tom was right about this part. That step gives you the non-numerical string characters. But then we do this:

汤姆在这方面是对的。该步骤为您提供非数字字符串字符。但是我们这样做:

NSString *trimmedString = [string stringByTrimmingCharactersInSet:searchSet];

return (string.length == trimmedString.length);

Tom's inverted character set can TRIM a string. So we can use that trim method to test if any non numerals exist in the string by comparing their lengths.

Tom 的倒置字符集可以修剪字符串。所以我们可以使用修剪方法通过比较它们的长度来测试字符串中是否存在任何非数字。

回答by sinoptic

For simple numbers like "12234" or "231231.23123" the answer can be simple.

对于像“12234”或“231231.23123”这样的简单数字,答案可能很简单。

There is a transformation law for int numbers: when string with integer transforms to int (or long) number and then, again, transforms it back to another string these strings will be equal.

int 数有一个转换法则:当带有整数的字符串转换为 int(或长)数,然后再次将其转换回另一个字符串时,这些字符串将相等。

In Objective C it will looks like:

在 Objective C 中,它看起来像:

NSString *numStr=@"1234",*num2Str=nil;
num2Str=[NSString stringWithFormat:@"%lld",numStr.longlongValue];

if([numStr isEqualToString: num2Str]) NSLog(@"numStr is an integer number!");

By using this transformation law we can create solution
to detect doubleor longnumbers:

通过使用这个转换定律,我们可以创建解决方案
来检测doublelong数字:

NSString *numStr=@"12134.343"
NSArray *numList=[numStr componentsSeparatedByString:@"."];

if([[NSString stringWithFormat:@"%lld", numStr.longLongValue] isEqualToString:numStr]) NSLog(@"numStr is an integer number"); 
else 
if( numList.count==2 &&
               [[NSString stringWithFormat:@"%lld",((NSString*)numList[0]).longLongValue] isEqualToString:(NSString*)numList[0]] &&
               [[NSString stringWithFormat:@"%lld",((NSString*)numList[1]).longLongValue] isEqualToString:(NSString*)numList[1]] )
            NSLog(@"numStr is a double number");
else 
NSLog(@"numStr is not a number");

I did not copy the code above from my work code so can be some mistakes, but I think the main point is clear. Of course this solution doesn't work with numbers like "1E100", as well it doesn't take in account size of integer and fractional part. By using the law described above you can do whatever number detection you need.

我没有从我的工作代码中复制上面的代码,所以可能会有一些错误,但我认为要点很清楚。当然,这个解决方案不适用于像“1E100”这样的数字,也没有考虑整数和小数部分的大小。通过使用上述定律,您可以进行任何您需要的数字检测。