Finding out whether a string is numeric or not

前端 未结 18 1646
一个人的身影
一个人的身影 2020-12-07 15:24

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSS         


        
18条回答
  •  离开以前
    2020-12-07 16:14

    This original question was about Objective-C, but it was also posted years before Swift was announced. So, if you're coming here from Google and are looking for a solution that uses Swift, here you go:

    let testString = "12345"
    let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    
    if testString.rangeOfCharacterFromSet(badCharacters) == nil {
        print("Test string was a number")
    } else {
        print("Test string contained non-digit characters.")
    }
    

提交回复
热议问题