如何确定各种字符串中是否包含2个或更多单词

问题描述 投票:0回答:1

我有一种情况,其中值包含多个字段,并提供一个搜索栏,用户可以在其中输入可以在这些字段之间拆分的短语。

以下是来自操场的简短样本,说明了我想要完成的任务。

import Foundation

struct Item {
    let name: String
    let size: String
}
let itemA = Item(name: "stuff", size: "Large")
let itemB = Item(name: "something", size: "X-Large")
let items = [itemA, itemB]

let singleSearch = "stuff"
let singleFound = items.filter { $0.name.localizedStandardContains(singleSearch) ||
    $0.size.localizedStandardContains(singleSearch)
}
print(singleFound) // ItemA

let multiSearch = "stuff large"
let multiFound = items.filter { $0.name.localizedStandardContains(multiSearch) ||
    $0.size.localizedStandardContains(multiSearch)
}

print(multiFound) // Nothing found, expect to see itemA

此外,它必须能够在用户搜索时处理部分单词,以支持缩小可见选项。

let partialSearch = "stuff l"
let partialFound = items.filter { $0.name.localizedStandardContains(partialSearch) ||
    $0.size.localizedStandardContains(partialSearch)
}

print(partialFound) // Nothing found, expect to see itemA

我怀疑我可能需要将搜索项分成一个数组并单独处理每个单词,并查看组合检查的结果。我担心的是实际实施的领域要多得多,所以这可能是不切实际的。

ios swift string
1个回答
1
投票

作为快速解决方案,您可以执行以下操作

let multiSearch = "st la"
let trimmed = multiSearch.trimmingCharacters(in: .whitespacesAndNewlines)
let multiSearchComponents = trimmed.components(separatedBy: " ")

var filtered = items
multiSearchComponents.forEach { searchTerm in
    filtered = filtered.filter { item in
        item.name.localizedStandardContains(searchTerm) || item.size.localizedStandardContains(searchTerm)
    }
}

print(filtered) //Prints itemA
© www.soinside.com 2019 - 2024. All rights reserved.