Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if string contains any element of a string array

How would I detect if a string contains any member of an array of strings (words)?

Here is the array:

let str:String = "house near the beach"
 let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]

The following is not compiling

let match:Bool = wordGroups.contains(where: str.contains)
like image 469
user1904273 Avatar asked Oct 08 '18 22:10

user1904273


3 Answers

You can try

let str = Set("house near the beach")
let match = wordGroups.filter { str.contains($0) }.count != 0
like image 95
Sh_Khan Avatar answered Sep 24 '22 06:09

Sh_Khan


In additional to answer of @Sh_Khan, if you want match some word from group:

let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
let worlds = wordGroups.flatMap { $0.components(separatedBy: " ")}
let match = worlds.filter { str.range(of:$0) != nil }.count != 0
like image 25
Nikdemm Avatar answered Sep 25 '22 06:09

Nikdemm


I am using String extension:

extension String {
    func contains(_ strings: [String]) -> Bool {
        strings.contains { contains($0) }
    }
}

Use case:

let str = "house near the beach"
let wordGroups = ["beach","waterfront", "with a water view", "near ocean", "close to water"]
let haveWord = str.contains(wordGroups)
like image 28
Ramis Avatar answered Sep 21 '22 06:09

Ramis