Swift:检查String是否在Array中有元素

时间:2015-10-19 00:22:44

标签: arrays string swift

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

我试过了,但我认为这太长了。想象一下,如果我想要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

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

let vowels = ["a", "e", "i", "o", "u"]
if typeString.containsString("\(vowels)") {
print("yes")
} else {
print("no")
}
// no
不过,我还是个新手还在学习。希望有人能提供帮助。感谢

2 个答案:

答案 0 :(得分:5)

let str = "Hello, playground."
let vogalsSet = CharacterSet(charactersIn: "aeiou")
if str.components(separatedBy: vogalsSet).first != str {
    print("at least one character was found")
} else {
    print("not found")
}

或者您也可以检查rangeOfCharacter(from aSet: CharacterSet)!= nil

if str.rangeOfCharacter(from: vogalsSet) != nil {
    print("at least one character was found")
} else {
    print("not found")
}

答案 1 :(得分: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")