5

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

2
  • Do you understand why your second attempt failed? That will help you solve this problem. Commented Oct 19, 2015 at 0:29
  • @aaron Yes, I think it is because I did put the whole array in containsString but I'm not sure how to check at least one of the array contains the string. Commented Oct 19, 2015 at 0:49

2 Answers 2

7

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")
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.