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

后端 未结 5 790
执念已碎
执念已碎 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:18

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

    extension String {
        func containsWhitespaceAndNewlines() -> Bool {
            return rangeOfCharacter(from: .whitespacesAndNewlines) != nil
        }
    }
    
    // Usage
    "hello, world!".containsWhitespaceAndNewlines() // true
    "hello,world!".containsWhitespaceAndNewlines() // false
    

提交回复
热议问题