android - Kotlin 在字符串列表中查找子字符串

标签 android string list search kotlin

我有一个字符串,它是一个产品名称:

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/

相关文章:

android - 当 IntentService 启动时,Application 对象会启动吗?

java - 如何将 facebook 响应日期转换为 unix 时间戳

swift - fatal error : Can't form a Character from an empty String

python - 根据给定条件组成一个数

python - 在字典列表上进行以下转换的 Pythonic 方式是什么?

android - 无法通过 ?attr 设置标题首选项图标

android - 打包/Maven 化公共(public)软件组件

python - 带有转义字符的 json.loads

c++ - 如何拆分包含字符和数字的字符串值

python - 使用 Python 将字典分类的最佳方法