How to check if NSString is contains a numeric value?

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

    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 entire string is numerical. Try this:

    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.

提交回复
热议问题