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

北战南征 提交于 2019-12-02 22:38:00

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

Shorter extension (swift 4.1)

extension String {
    var containsWhitespace : Bool {
        return(self.rangeOfCharacter(from: .whitespacesAndNewlines) != nil)
    }
}

You can change the .whitespacesAndNewlines with any other CharacterSet like this:

extension String {
    var containsDigits : Bool {
        return(self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil)
    }
}

I created a String extension that does exactly this, hope it's useful.

extension String {

    func containsWhiteSpace() -> Bool {

        // check if there's a range for a whitespace
        let range = self.rangeOfCharacterFromSet(.whitespaceCharacterSet())

        // returns false when there's no range for whitespace
        if let _ = range {
            return true
        } else {
            return false
        }
    }
}

This answer works with text fields. I was going crazy trying to search for whitespace on a UItextfield without searching the string content of it. This works for UItextfields:

Swift 4:

    if (textField.text?.contains(" "))!{
        print("Has space")
    }else{
        print("Does not have space")
    }

This is for a regular string, also in swift 4

    if string.contains(" "){
        print("Has space")
    }else{
        print("Does not have space")
    }

For Swift 5

extension String {

    func containsWhiteSpace() -> Bool {

        // check if there's a range for a whitespace
        let range = self.rangeOfCharacter(from: .whitespacesAndNewlines)

        // returns false when there's no range for whitespace
        if let _ = range {
            return true
        } else {
            return false
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!