如何检测字符串是否包含字符串(单词)数组的任何成员?
这是数组:
let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
以下内容未编译
let match:Bool = wordGroups.contains(where: str.contains)
答案 0 :(得分:2)
除了@Sh_Khan的答案外,如果您想匹配组中的某个单词:
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
答案 1 :(得分:1)
您可以尝试
let str = Set("house near the beach")
let match = wordGroups.filter { str.contains($0) }.count != 0
答案 2 :(得分:1)
我正在使用 String 扩展名:
extension String {
func contains(_ strings: [String]) -> Bool {
strings.contains { contains($0) }
}
}
用例:
let str = "house near the beach"
let wordGroups = ["beach","waterfront", "with a water view", "near ocean", "close to water"]
let haveWord = str.contains(wordGroups)