Swift 字符串比较字符

Swift string compare characters

我希望将用户输入的字符串与其他 3 个字符串进行比较。如果用户输入的字符串包含其他字符串包含的任何字符,我想做一件事,如果没有则做其他事情

案例 1: 字符串 1 = abc 字符串 2 = abc string3 = abc

userEnter = fgh

> since none of the letters match do one thing

案例 2: 字符串 1 = abc 字符串 2 = fbc string3 = abc

userEnter = fgh

> one letter from userEnter is found in the other 3 strings do another thing...

完全不确定如何比较 swift 中的字符串或如何访问单个字符。我习惯了一切都是字符数组的 C..

Swift 中的字符串与 C 相比是一个不同的野兽,不仅仅是字符数组(我建议 Swift 博客上有一个 nice article你去阅读,顺便说一句)。在您的情况下,您可以使用 String 类型的 characters 属性,这基本上是一个视图,可让您访问字符串中的各个字符。

例如,您可以这样做:

let strings = ["abc", "abc", "abc"]

let chars = strings.reduce(Set<Character>()) { 
    (var output: Set<Character>, string: String) -> Set<Character> in

    string.characters.forEach() {
        output.insert([=10=])
    }

    return output
}

let test = "fgh"

if test.characters.contains({ chars.contains([=10=]) }) {
    print("Do one thing")
} else {
    print("Do another thing")
}

在上面的代码中,strings 数组包含所有 3 个比较对象字符串。然后有一个由它们创建的集合 chars,其中包含所有字符串中的所有单个字符。最后还有一个包含用户输入的 test