Swift:检查字符串是否包含数组中的元素

5

我想检查一个字符串是否包含数组中至少一个元素。

我尝试了这种方法,但我认为它太长了。如果我想在if语句中使用整个字母表,那该怎么办呢?我希望有一种更好的方法来实现这个功能。

var str = "Hello, playground."

let typeString = NSString(string: str)

if typeString.containsString("a") || typeString.containsString("e") || typeString.containsString("i") || typeString.containsString("o") || typeString.containsString("u") {
print("yes")
} else { 
print("no")
}
// yes

我尝试使用数组,但它不起作用。它需要数组中的所有元素都具有“yes”的结果。

let vowels = ["a", "e", "i", "o", "u"]
if typeString.containsString("\(vowels)") {
print("yes")
} else {
print("no")
}
// no

顺便说一下,我还是个新手,正在学习中。希望有人能帮助我。谢谢。


你明白你的第二次尝试为什么失败了吗?这会帮助你解决这个问题。 - Aaron Brager
@aaron 是的,我认为是因为我把整个数组都放在了containsString里,但我不确定如何检查数组中至少有一个包含该字符串。 - Chris Tope
2个回答

7

您可以使用字符串字符创建两个集合,并检查它们的交集:

let str = "Hello, playground."
let set = Set("aeiou")
let intersection = Set(str).intersection(set)
if !intersection.isEmpty {
    print("Vogals found:", intersection)                        // {"u", "o", "e", "a"}
    print("Vogals not found:", set.subtracting(intersection))   // {"i"}
} else {
    print("No vogal found")
}

0

尝试使用这个switch语句。

let mySentence = "Hello Motto"
var findMyVowel: Character = "a" 
switch findMyVowel { 
case "a","e","i","o","u": 
    print("yes") 
default:
    print("no")
} 
mySentence.containsString("e")

let sentence = "Hello Motto" let containsVowel = sentence.contains { switch $0 { case "a","e","i","o","u": return true default: return false } } print(containsVowel) - Leo Dabus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接