检测字符串是否包含字符串数组的任何元素

2024-02-12

如何检测字符串是否包含字符串数组(单词)的任何成员?

这是数组:

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)

我在用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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检测字符串是否包含字符串数组的任何元素 的相关文章

随机推荐