在数组中查找单词

时间:2019-05-09 18:14:18

标签: swift

如何检查字符串中是否有单词?

例如:

let arr = ["This", "is", "Array", "of", "String"]
let str = "The word String is exists"

结果应为:

  

找到的单词:“字符串”,“是”

5 个答案:

答案 0 :(得分:2)

这是一个不太天真的解决方案,适用于包含标点符号的字符串。

这首先使用本地化规则将字符串拆分为单词。然后找到两个单词数组的交集。

func findWords(text: String, words: [String]) -> [String] {
    var textWords: Set<String> = []
    text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: [.byWords, .localized]) { (word, _, _, _) in
        if let word = word {
            textWords.insert(word)
        }
    }

    let matches = textWords.intersection(words)

    return Array(matches)
}

print(findWords(text: "The word String is exists", words: ["This", "is", "Array", "of", "String"]))
print(findWords(text: "Hello there. How are you today?", words: ["there", "is", "today"]))

输出:

  

[“ String”,“是”]
  [“有”,“今天”]

在撰写本文时,没有其他解决方案可用于第二个示例。

答案 1 :(得分:0)

let arr = ["This", "is", "Array", "of", "String"]
let str = "The word String is exists"
let set1 = Set(str.components(separatedBy: .whitespaces).filter { !$0.isEmpty })
let set2 = Set(arr)
let result = set1.intersection(set2)
print(result)

答案 2 :(得分:0)

您可以尝试

let str = "The word String is exists"
let all = str.components(separatedBy:" ")
let arr = ["This", "is", "Array", "of", "String"]
let res =  arr.filter { all.contains($0) } // or contains(where

答案 3 :(得分:0)

尝试以下操作:

var resArray = [String]()
let wordArr = str.components(separatedBy: " ")
for s in wordArr {
     if arr.contains(s) {
       resArray.append(s)
    }
}

答案 4 :(得分:0)

您可以通过设置交集直接获得结果:

let arr = ["This", "is", "Array", "of", "String"]
let str = "The word String is exists"
let separators = CharacterSet.alphanumerics.inverted
let result     = Set(arr).intersection(str.components(separatedBy: separators))