确定字符串是否包含Swift中集合中的字符的最佳方法是什么

时间:2015-02-12 19:29:05

标签: swift

我需要确定字符串是否包含我定义的自定义集中的任何字符。

我在this帖子中看到,您可以使用rangeOfString来确定字符串是否包含另一个字符串。当然,如果您一次测试一个角色,这也适用于角色。

我想知道最好的办法是什么。

10 个答案:

答案 0 :(得分:54)

您可以创建包含自定义字符集的CharacterSet 然后根据此字符集测试成员资格:

斯威夫特3:

let charset = CharacterSet(charactersIn: "aw")
if str.rangeOfCharacter(from: charset) != nil {
    print("yes")
}

对于不区分大小写的比较,请使用

if str.lowercased().rangeOfCharacter(from: charset) != nil {
    print("yes")
}

(假设字符集仅包含小写字母)。

Swift 2:

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset) != nil {
    print("yes")
}

Swift 1.2

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {
    println("yes")
}

答案 1 :(得分:8)

从Swift 1.2中,您可以使用Set

执行此操作
var str = "Hello, World!"
let charset: Set<Character> = ["e", "n"]

charset.isSubsetOf(str)     // `true` if `str` contains all characters in `charset`
charset.isDisjointWith(str) // `true` if `str` does not contains any characters in `charset`
charset.intersect(str)      // set of characters both `str` and `charset` contains.

Swift 3或更高版本

let isSubset = charset.isSubset(of: str)        // `true` if `str` contains all characters in `charset`
let isDisjoint = charset.isDisjoint(with: str)  // `true` if `str` does not contains any characters in `charset`
let intersection = charset.intersection(str)    // set of characters both `str` and `charset` contains.
print(intersection.count)   // 1

答案 2 :(得分:6)

Nice Swift4 解决方案,检查是否包含字母:

CharacterSet.letters.isSuperset(of: CharacterSet(charactersIn: myString) // returns BOOL

当您需要验证自定义字符集的字符串时的另一种情况。例如,如果字符串包含字母和(例如)破折号和空格:

let customSet: CharacterSet = [" ", "-"]
let finalSet = CharacterSet.letters.union(customSet)
finalSet.isSuperset(of: CharacterSet(charactersIn: myString)) // BOOL

希望有一天能帮到某人:)

答案 3 :(得分:4)

使用 Swift 3 确定您的字符串是否包含特定CharacterSet 中的字符:

    let letters = CharacterSet.alphanumerics
    let string = "my-string_"
    if (string.trimmingCharacters(in: letters) != "") {
        print("Invalid characters in string.")
    }
    else {
        print("Only letters and numbers.")
    }

答案 4 :(得分:4)

<强> swift3

var str = "Hello, playground"
let res = str.characters.contains { ["x", "z"].contains( $0 ) }

答案 5 :(得分:4)

Swift 3示例:

extension String{
    var isContainsLetters : Bool{
        let letters = CharacterSet.letters
        return self.rangeOfCharacter(from: letters) != nil
    }
}

用法:

"123".isContainsLetters // false

答案 6 :(得分:2)

你可以这样做:

var string = "Hello, World!"

if string.rangeOfString("W") != nil {
     println("exists")
} else {
     println("doesn't exist")
}

// alternative: not case sensitive
if string.lowercaseString.rangeOfString("w") != nil {
     println("exists")
} else {
     println("doesn't exist")
}

答案 7 :(得分:2)

func isAnyCharacter( from charSetString: String, containedIn string: String ) -> Bool
{
    return Set( charSetString.characters ).isDisjointWith( Set( string.characters) ) == false
}

答案 8 :(得分:2)

Swift 4

let myString = "Some Words"

if myString.contains("Some"){
    print("myString contains the word `Some`")
}else{
    print("myString does NOT contain the word `Some`")
}

斯威夫特3:

let myString = "Some Words"

if (myString.range(of: "Some") != nil){
    print("myString contains the word `Some`")
}else{
    print("Word does not contain `Some`")
}

答案 9 :(得分:0)

在Swift 4.2中像这样使用

class SpinnerAdapter(var name: List<PaymentMethod>) {
init {
    name.map{ 
        when(name.first()){
            is Card -> {
                //  do something
            }
            is Currency -> {
                //  do something
            }
        }
    }
}