Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search multiple words in one string in swift

Tags:

string

swift

I have a long string in swift3 and want to check if it contains word1 and word2. It could also be more than 2 search words. I found out 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 this seems very complicated, is there not an easier way to solve this? (Xcode8 and swift3)

like image 552
A. Kniesel Avatar asked Jan 27 '17 20:01

A. Kniesel


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 little more efficient than your solution because the contains method returns as soon as a "not contained" word is found.

As of Swift 4 or later, you can use allSatisfy:

let success = wordList.allSatisfy(text.contains)
like image 157
Martin R Avatar answered Nov 07 '22 19:11

Martin R


A more Swifty solution that will stop searching after it found a non-existent 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 it which stops after it found a non-match:

let match = textArray.first(where: { !text.contains($0) }) == nil
like image 3
Code Different Avatar answered Nov 07 '22 19:11

Code Different


Another possibility is regular expressions:

// *'s 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")
}
like image 3
Michael Dautermann Avatar answered Nov 07 '22 18:11

Michael Dautermann