0

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"
]
1
  • 1
    So if string contains "beaches" is "beach" from wordGroups a match then? Commented Oct 28, 2021 at 20:44

2 Answers 2

1

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

As suggested in the comments the above loop can be replace with a shorter contains version

let isMatch = wordGroups.contains { 
    string.range(of: "\\b\($0)\\b", options: .regularExpression) != nil
}

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

Sign up to request clarification or add additional context in comments.

6 Comments

why not contains(where:) instead of first(where:) != nil
No particular reason really, first(where) was the first (duh) one that came to mind but not needing != nil is of course even clearer. Thanks.
You can still use contains { ... } in the first solution
@Sulthan not sure I understand, wouldn't that make it the same as the second solution?
@JoakimDanielson I think the important part of the first solution is the use of regular expression, not the iteration. Therefore you can still use wordGroups.contains { word in string.range(of: "\\b\(word)\\b", options: .regularExpression) != nil }
|
1

Wasn't too sure how to interpret "to see if it contains any words of the substring within the array of wordGroups", but this solution checks to see if any words of your input string are contained in any substring of your word groups.

func containsWord(str: String, wordGroups: [String]) -> Bool {
    // Get all the words from your input string
    let words = str.split(separator: " ")
    
    
    for group in wordGroups {
        // Put all the words in the group into set to improve lookup time
        let set = Set(group.split(separator: " "))
        
        for word in words {
            if set.contains(word) {
                return true
            }
        }
    }
    
    return false
}

Comments

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.