Swift 3 String Contains Exact Sentence / Word

Viewed 2660

I would like to know a simple algorithm to determine if a string contains exact sentence or word.

I'm not looking for:

string.contains(anotherString)

Here's why:

let string = "I know your name"
string.contains("you") // Will return true

In the example above, it returns true because if find "you" in the word "your". I want a method that will return false in that condition.

For example:

let string = "I am learning Swift"

// Let's say we make a method using extension called contains(exact:)
string.contains(exact: "learn") // return false

The method contains(exact:) will return false since "learn" is not equal with "learning"

Another example:

let string = "Healthy low carb diets"
string.contains(exact: "low carb diet") // return false

What's the algorithm to get that result in Swift 3? Or is there predefined method for this?

3 Answers
func containsExact(_ findString: String, _ inString: String) -> Bool {
    let expression = "\\b\(findString)\\b"
    return inString.range(of: expression, options: .regularExpression) != nil
}
Related