簡體   English   中英

斯威夫特字符串比較字符

[英]Swift string compare characters

我想將用戶輸入的字符串與其他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...

完全不知道如何快速比較字符串或如何訪問單個字符。 我習慣了C,這里的所有內容都是char數組。

與C相比,Swift中的字符串是不同的野獸,而不僅僅是字符數組(Swift博客上有一篇不錯的文章 ,我建議您閱讀,順便說一句)。 在您的情況下,您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM