搜索多个单词,忽略Swift中的顺序 [英] Search for multiple words ignoring the order in Swift
本文介绍了搜索多个单词,忽略Swift中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一个 UITextField
,可以在其中输入搜索字符串,它将按特定顺序返回包含该文本的数组中的任何字符串.但是,我想使搜索每个单词并忽略数组中字符串的顺序成为可能.
I currently have a UITextField
where I can enter a search string and it will return any of the strings in an array that contain that text, in that specific order. However, I want to make it possible to search on every word and ignore the order of the strings in the array.
var results = [String]()
let filterArray = ["Big green bubble", "Red bubble", "A bubble in green", "Small green bubble", "This bubble is green"]
let textString = "green bubble"
for i in 0 ..< filterArray.count {
let checkString = filterArray[i]
let filterRange = (checkString as NSString).range(of: textString, options: .caseInsensitive)
if filterRange.location != NSNotFound {
results.append(checkString)
}
}
print(results) // returns ["Big green bubble", "Small green bubble"]
我希望它也包含绿色气泡" 和这个气泡绿色" ,因为它包含了我要搜索的每个单词.有什么想法吗?
I wish it would also include "A bubble in green" and "This bubble is green", because it contains every word I am searching for. Any ideas?
推荐答案
只需过滤来自 filterArray
的元素,其中包含这两个词
Just filter elements from filterArray
which contains both of these words
let filterArray = ["Big green bubble", "Red bubble", "A bubble in green", "Small green bubble", "This bubble is green"]
let textString = "green bubble".lowercased()
let words = textString.components(separatedBy: " ")
let results = filterArray.map { $0.lowercased() }.filter { string in words.allSatisfy { string.components(separatedBy: " ").contains($0) } }
print(results) /* ["Big green bubble", "A bubble in green", "Small green bubble", "This bubble is green"] */
这篇关于搜索多个单词,忽略Swift中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文