A. Kniesel
A. Kniesel

Reputation: 163

Search multiple words in one string in 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)

Upvotes: 9

Views: 8010

Answers (3)

Martin R
Martin R

Reputation: 540025

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)

Upvotes: 14

Michael Dautermann
Michael Dautermann

Reputation: 89559

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

Upvotes: 3

Code Different
Code Different

Reputation: 93191

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

Upvotes: 3

Related Questions