How to check if NSString is contains a numeric value?

前端 未结 7 2097
走了就别回头了
走了就别回头了 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:38

    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.

    For instance, " 13 " -> 13, "42foo" -> 42 and "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:

    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 larger than that of an integer (even a 64-bit integer).

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

提交回复
热议问题