How to check if NSString is contains a numeric value?

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

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

    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!

提交回复
热议问题