【问题标题】:Swift string compare charactersSwift字符串比较字符
【发布时间】:2026-01-28 11:20:24
【问题描述】:

我希望将用户输入的字符串与其他 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...

完全不知道如何快速比较字符串或如何访问单个字符。我习惯了 C 中的一切都是 char 数组..

【问题讨论】:

  • 简单的== 有效吗?例如,if str1 == str2

标签: arrays string swift character


【解决方案1】:

与 C 相比,Swift 中的字符串是一个不同的野兽,不仅仅是字符数组(我建议您阅读 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($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

【讨论】: