Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 String Contains Exact Sentence / Word

Tags:

swift

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?

like image 337
Edward Anthony Avatar asked Aug 01 '17 11:08

Edward Anthony


2 Answers

A solution is Regular Expression which is able to check for word boundaries.

This is a simple String extension, the pattern searches for the query string wrapped in word boundaries (\b)

extension String {
    func contains(word : String) -> Bool
    {
        do {
            let regex = try NSRegularExpression(pattern: "\\b\(word)\\b")
            return regex.numberOfMatches(in: self, range: NSRange(word.startIndex..., in: word)) > 0
        } catch {
            return false
        }
    }
}

Or – thanks to Sulthan – still simpler

extension String {
    func contains(word : String) -> Bool
    {
        return self.range(of: "\\b\(word)\\b", options: .regularExpression) != nil
    }
}

Usage:

let string = "I know your name"
string.contains(word:"your") // true
string.contains(word:"you") // false
like image 179
vadian Avatar answered Sep 29 '22 07:09

vadian


A regexless solution would be something like:

yourString.components(separatedBy: CharacterSet.alphanumerics.inverted)
    .filter { $0 != "" } // this is here os that it always evaluates to false if wordToFind is "". Feel free to remove this line if you don't need it.
    .contains(wordToFind)

This will treat every non-alphanumeric character as a word boundary.

like image 27
Sweeper Avatar answered Sep 29 '22 07:09

Sweeper