Search multiple words on one line in swift

I have a long string in swift3 and want to check if it contains word1 and word2. It can be more than two search words. I found the following solution:

var Text = "Hello Swift-world" var TextArray = ["Hello", "world"] var count = 0 for n in 0..<TextArray.count { if (Text.contains(TextArray[n])) { count += 1 } } if (count == TextArray.count) { print ("success") } 

But it seems very complicated, is there an easier way to solve this? (Xcode8 and swift3)

+5
source share
3 answers

If you are looking for less code:

 let text = "Hello Swift-world" let wordList = ["Hello", "world"] let success = !wordList.contains(where: { !text.contains($0) }) print(success) 

It is also a bit more efficient than your solution, because the contains method returns as soon as the word "does not contain".

+5
source

More Swifty solution that will stop the search after it finds a nonexistent word:

 var text = "Hello Swift-world" var textArray = ["Hello", "world"] let match = textArray.reduce(true) { !$0 ? false : (text.range(of: $1) != nil ) } 

Another way to do this, which stops after it finds a mismatch:

 let match = textArray.first(where: { !text.contains($0) }) == nil 
+2
source

Another possibility is regular expressions :

 // * are wildcards let regexp = "(?=.*Hello*)(?=.*world*)" if let range = Text.range(of:regexp, options: .regularExpression) { print("this string contains Hello world") } else { print("this string doesn't have the words we want") } 
+1
source

Source: https://habr.com/ru/post/1263470/


All Articles