我有一个字符串,它是一个产品名称:
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
帮我把那些假的变成真:)
最佳答案
比如:
fun match(product: Array<String>, terms: Array<String>): Boolean {
return terms.all { term -> product.any { word -> word.contains(term) } }
}
有测试:
import java.util.*
fun main(args: Array<String>) {
val product = arrayOf("this", "is", "an", "example", "product", "name")
val tests = mapOf(
arrayOf("example", "product") to true,
arrayOf("an", "name") to true,
arrayOf("mple", "name") to true,
arrayOf("example", "name") to true,
arrayOf("this", "prod") to true
)
tests.forEach { (terms, result) ->
System.out.println(search(product, terms) == result)
}
}
fun match(product: Array<String>, terms: Array<String>): Boolean {
return terms.all { term -> product.any { word -> word.contains(term) } }
}
您还有其他不起作用的示例/测试吗?
关于android - Kotlin 在字符串列表中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49872909/