【发布时间】:2018-09-27 02:44:04
【问题描述】:
我有一个字符串,它是产品名称:
val productName = "7 UP pov.a. 0,25 (24)"
还有一个用户在搜索栏中输入的字符串,比如说:
val userInput = "up 0,25"
我正在使用这种方法对 productName 和 userInput 进行规范化:
private fun normalizeQuery(query: String): List<String> {
val list = Normalizer.normalize(query.toLowerCase(), Normalizer.Form.NFD)
.replace("\\p{M}".toRegex(), "")
.split(" ")
.toMutableList()
for (word in list) if (word == " ") list.remove(word)
return list
}
现在我有 2 个标准化字符串列表(所有内容都是小写的,没有空字符,也没有重音字母,例如 Č -> c、Ž -> z、ž -> z、š -> s、ć -> c等):
product = [7, up, pov.a., 0,25, (24)]
input = [up, 0,25]
现在,如果产品中的字符串包含来自输入的每个字符串,但即使是子字符串,我希望(在这些示例中为简单起见)返回 true,例如
input = [0,2, up] -> true
input = [up, 25] -> true
input = [pov, 7] -> true
input = [v.a., 4), up] -> true
另一个想要输出的例子:
product = [this, is, an, example, product, name]
input = [example, product] -> true
input = [mple, name] -> true
input = [this, prod] -> true
我尝试了什么:
A) 简单有效的方法?
if (product.containsAll(input)) outputList.put(key, ActivityMain.products!![key]!!)
但这只有在输入包含与产品中完全相同的字符串时才给我我想要的,例如:
product = [this, is, an, example, product, name]
input = [example, product] -> true
input = [an, name] -> true
input = [mple, name] -> false
input = [example, name] -> true
input = [this, prod] -> false
B) 复杂的方式,给了我想要的,但有时会出现不想要的结果:
val wordCount = input.size
var hit = 0
for (word in input)
for (word2 in product)
if (word2.contains(word))
hit++
if (hit >= wordCount)
outputList.put(key, ActivityMain.products!![key]!!)
hit = 0
帮我把那些假的变成真的:)
【问题讨论】:
-
您希望
[product, example]有什么行为? ([example, product]的反面
标签: android string list search kotlin