简体   繁体   English

斯威夫特字符串比较字符

[英]Swift string compare characters

I am looking to compare a string that the user enters to 3 other strings. 我想将用户输入的字符串与其他3个字符串进行比较。 If the user entered string has any of the characters that the other strings contain I want to do one thing and if not something else 如果用户输入的字符串具有其他字符串包含的任何字符,我想做一件事,如果不是

case 1: string1 = abc string2 = abc string3 = abc 情况1:string1 = abc string2 = abc string3 = abc

userEnter = fgh

> since none of the letters match do one thing

case 2: string1 = abc string2 = fbc string3 = abc 情况2:string1 = abc string2 = fbc string3 = abc

userEnter = fgh

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

Not sure how to compare strings in swift at all or how to access individual characters. 完全不知道如何快速比较字符串或如何访问单个字符。 I am used to C where everything is a char array.. 我习惯了C,这里的所有内容都是char数组。

Strings in Swift are a different different kid of beast compared to C and are not just arrays of characters (there is a nice article at the Swift blog which I would suggest you to read, BTW). 与C相比,Swift中的字符串是不同的野兽,而不仅仅是字符数组(Swift博客上有一篇不错的文章 ,我建议您阅读,顺便说一句)。 In your case you can use characters property of the String type, which is basically a view that gives you access to individual characters in the string. 在您的情况下,您可以使用String类型的characters属性,该属性基本上是一个视图,可让您访问字符串中的各个字符。

For example, you could do: 例如,您可以这样做:

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")
}

In the above code strings array contains all your 3 compare-to strings. 在上面的代码strings数组中,包含所有3个“与”字符串。 Then there is a set chars created out of them that contains all the individual characters from all of the strings. 然后从中创建一个chars集,其中包含所有字符串中的所有单个字符。 And finally there is a test which contains user input. 最后是一个包含用户输入的test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM