简体   繁体   English

如何检查字符串是否包含空格/字母数字/等字符?

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

How can you use the "ctype.h" library in Swift to be able to use isAlpha or isSpace on characters?如何使用 Swift 中的“ctype.h”库来对字符使用isAlphaisSpace Or is there a better, Swift, way of doing it?或者有更好的 Swift 方法吗?

This question is answered, but it doesn't seem to work: Swift: how to find out if letter is Alphanumeric or Digit这个问题得到了回答,但它似乎不起作用: Swift: how to find if letter is Alphanumeric or Digit

It doesn't specify how to import the library.它没有指定如何导入库。 Could someone point me in the right direction?有人能指出我正确的方向吗?

Here's what I've got so far:这是我到目前为止所得到的:

extension String {
    subscript (i : Int) -> String {
        return String(Array(self)[i])
    }
}

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"

for var i=0; i<countElements(phrase); i++ {
    if whitespace.characterIsMember(phrase[i]) { //error
        println("char is whitespace")
    }
}

Use NSCharacter on the entire string,not character-by-character:在整个字符串上使用 NSCharacter,而不是逐个字符:

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)更短的扩展(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:您可以使用任何其他CharacterSet更改.whitespacesAndNewlines ,如下所示:

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.我创建了一个 String 扩展来完成这个,希望它有用。

extension String {
    func containsWhitespaceAndNewlines() -> Bool {
        return rangeOfCharacter(from: .whitespacesAndNewlines) != nil
    }
}

// Usage
"hello, world!".containsWhitespaceAndNewlines() // true
"hello,world!".containsWhitespaceAndNewlines() // 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.我疯狂地尝试在 UItextfield 上搜索空格而不搜索它的字符串内容。 This works for UItextfields:这适用于 UItextfields:

Swift 4:斯威夫特 4:

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

This is for a regular string, also in swift 4这是用于常规字符串,也在 swift 4

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

For Swift 5对于 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
        }
    }
}

This function will tell you if there is a whitespace between a string.这个函数会告诉你字符串之间是否有空格。 for example if you are trying to make sure the user enter a first and last name例如,如果您试图确保用户输入名字和姓氏

Swift 5斯威夫特 5

func validatTextField() -> Bool {
        var isValid = false
        if textField.text!.contains(" ") && !textField.text!.isEmpty{
            let cardHolderChar = textField.text!
            for i in cardHolderChar {
                if i == " " && i == cardHolderChar.last {
                    isValid = false
                }
                else {
                    isValid = true
                }
            }
        }
        return isValid
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM