How to check if NSString is contains a numeric value?

前端 未结 7 1977
走了就别回头了
走了就别回头了 2021-01-31 09:09

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 dif

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 09:22

    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.

提交回复
热议问题