[英]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.