我有一个产品名称字符串:
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个规范化字符串列表(一切都是小写,没有空字符,没有重音字母,例如Č - &gt; c,Ž - &gt; z,ž - &gt; z,š - &gt; s, ć - &gt; c等):
product = [7, up, pov.a., 0,25, (24)]
input = [up, 0,25]
现在我希望(为了这些示例中的简单)如果来自product的字符串包含来自输入的每个字符串,但甚至作为子字符串,则返回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
帮我把那些假的转换为真的:)
答案 0 :(得分:2)
如下:
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) } }
}
您是否有其他不起作用的示例/测试?