Swift字符串比较字符

时间:2015-11-16 05:45:04

标签: arrays string swift character

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

案例1:     string1 = abc     string2 = abc     string3 = abc

userEnter = fgh

> since none of the letters match do one thing

案例2:     string1 = abc     string2 = fbc     string3 = abc

userEnter = fgh

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

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

1 个答案:

答案 0 :(得分:0)

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

例如,你可以这样做:

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($0)
    }

    return output
}

let test = "fgh"

if test.characters.contains({ chars.contains($0) }) {
    print("Do one thing")
} else {
    print("Do another thing")
}

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