Home > other >  How to check if a string contains a substring within an array of strings in Swift?
How to check if a string contains a substring within an array of strings in Swift?

Time:10-29

I have a string "A very nice beach" and I want to be able to see if it contains any words of the substring within the array of wordGroups.

let string = "A very nice beach"

let wordGroups = [
    "beach",
    "waterfront",
    "with a water view",
    "near ocean",
    "close to water"
]

CodePudding user response:

First solution is for exactly matching the word or phrase in wordGroups using regex

var isMatch = false
for word in wordGroups {
    let regex = "\\b\(word)\\b"
    if string.range(of: regex, options: .regularExpression) != nil {
        isMatch = true
        break
    }
}

Second solution is for simply text if string contains the any of the strings in the array

let isMatch2 = wordGroups.contains(where: string.contains)

So for "A very nice beach" both returns true but for "Some very nice beaches" only the second one returns true

CodePudding user response:

I thought of a solution using filter and determining the count but I felt like it was a workaround and it's brute-forcing through each element.

var isMatch = wordGroups.filter { string.contains($0) }.count > 0
  • Related