How can I check to see if a string contains characters of whitespace/alphanumeric/etc?

后端 未结 5 786
执念已碎
执念已碎 2021-02-04 02:19

How can you use the \"ctype.h\" library in Swift to be able to use isAlpha or isSpace on characters? Or is there a better, Swift, way of doing it?

5条回答
  •  温柔的废话
    2021-02-04 03:05

    Use NSCharacter on the entire string,not character-by-character:

    let whitespace = NSCharacterSet.whitespaceCharacterSet()
    
    let phrase = "Test case"
    let range = phrase.rangeOfCharacterFromSet(whitespace)
    
    // range will be nil if no whitespace is found
    if let test = range {
        println("whitespace found")
    }
    else {
        println("whitespace not found")
    }
    

    Output:

    whitespace found
    

提交回复
热议问题