【问题标题】:Kotlin find substring in list of stringsKotlin 在字符串列表中查找子字符串
【发布时间】: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


【解决方案1】:

类似的东西呢:

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) } }
}

您还有其他不起作用的示例/测试吗?

【讨论】:

  • 你的“匹配”方法效果很好,非常感谢,我以后会用这个方法
猜你喜欢
  • 2012-05-16
  • 2023-04-03
  • 2021-04-21
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多