Reputation: 133
I want to check if a string contains at least one element in an array.
I tried this but I think it's too long. Imagine if I want all the alphabet in the if statement. I hope there is a proper way to do this.
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
I tried using an array but it doesn't work. It needs all of the elements in an array to have a result of "yes".
let vowels = ["a", "e", "i", "o", "u"]
if typeString.containsString("\(vowels)") {
print("yes")
} else {
print("no")
}
// no
Btw, I'm still a newbie and still learning. Hope someone can help. Thanks
Upvotes: 5
Views: 1239
Reputation: 236360
You can create two sets with the string characters and check its intersection:
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")
}
Upvotes: 7
Reputation: 509
Try using this switch statements.
let mySentence = "Hello Motto"
var findMyVowel: Character = "a"
switch findMyVowel {
case "a","e","i","o","u":
print("yes")
default:
print("no")
}
mySentence.containsString("e")
Upvotes: 0