Kotlin find substring in list of strings

fkvestak

I have a string which is a product name:

val productName = "7 UP pov.a. 0,25 (24)"

and another string which is a users input in search bar, let's say:

val userInput = "up 0,25"

I'm normalizing both productName and userInput with this method:

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

}

Now I have 2 lists of normalized strings (everything is lowercase, without empty chars, and without accented letters, e.g. Č -> c, Ž -> z, ž -> z, š -> s, ć -> c, etc.):

product = [7, up, pov.a., 0,25, (24)]
input = [up, 0,25]

Now I want (for the sake of simplicity in these examples) to return true if strings from product contains every string from input, but even as a substring, e.g.

input = [0,2, up] -> true
input = [up, 25] -> true
input = [pov, 7] -> true
input = [v.a., 4), up] -> true

Another example of wanted output:

product = [this, is, an, example, product, name]
input = [example, product] -> true
input = [mple, name] -> true
input = [this, prod] -> true

What I tried:

A) Easy and efficient way?

if (product.containsAll(input)) outputList.put(key, ActivityMain.products!![key]!!)

But this gives me what I want only if input contains EXACT same strings as in product, e.g.:

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) Complicated way, gives me what I want, but sometimes there are unwanted results:

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

Help me to convert those false's into true's :)

Kevin Robatel

What about something like:

fun match(product: Array<String>, terms: Array<String>): Boolean {
    return terms.all { term -> product.any { word -> word.contains(term) } }
}

With tests:

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

Do you have other example/tests that doesn't work?

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Find differences in list of strings

Fast way to find strings in set of strings containing substring

Fast way to find strings in set of strings containing substring

Find the most common substring in an array of strings with a given sequence length

How to find the two strings that occurs most in a list?

Comparing a string with a list of strings to find anagrams in Python

Common Substring of two strings

Kotlin 打印 List<Strings> 的所有組合

Javascript - Find a specfic property in object by value which is a list of strings

Find strings in strings

How to find a substring using regex

Using regex to find substring in Java

Use substring against a file with varied length strings

Check if an array of strings contains a substring in javascript

Splitting and sorting a list based on substring

Sort items in list by index of a substring in another list

What is the best way to find a list of several strings within a large text file

SQLAlchemy query to find and replace a substring if it exists in a column

Matlab: find the length of longest substring in sequence

substr to find all text before a wildcard substring

Convert list of strings to dictionary

Sort list of strings

String of list or strings to a tuple

Enumerate unique strings in list

given a list of strings in python

NameError when searching for substring in Python list

C # 구분 List <string> by substring

how to search for series of strings in a sentence in kotlin

check for multiple substring match in a list while iterating list

TOP 리스트

  1. 1

    Matlab의 반복 Sortino 비율

  2. 2

    ImageJ-히스토그램 빈을 변경할 때 최대, 최소 값이 변경되는 이유는 무엇입니까?

  3. 3

    Excel : 합계가 N보다 크거나 같은 상위 값 찾기

  4. 4

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  5. 5

    원-사각형 충돌의 충돌 측면을 찾는 문제

  6. 6

    Oracle VirtualBox-설치를 위해 게스트를 부팅 할 때 호스트 시스템이 충돌 함

  7. 7

    어떻게 아무리 "나쁜", ANY의 SSL 인증서와 HttpClient를 사용하지합니다

  8. 8

    Ubuntu는 GUI에서 암호로 사용자를 만듭니다.

  9. 9

    잘못된 상태 예외를 발생시키는 Apache PoolingHttpClientConnectionManager

  10. 10

    Python 사전을 사용하는 동안 "ValueError : could not convert string to float :"발생

  11. 11

    openCV python을 사용하여 텍스트 문서에서 워터 마크를 제거하는 방법은 무엇입니까?

  12. 12

    Vuetify 다중 선택 구성 요소에서 클릭 한 항목의 값 가져 오기

  13. 13

    C ++ VSCode에서 같은 줄에 중괄호 서식 지정

  14. 14

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  15. 15

    JQuery datepicker 기능이 인식되지 않거나 새 프로젝트에서 작동하지 않음

  16. 16

    cuda 11.1에서 Pytorch를 사용할 때 PyTorch가 작동하지 않음: Dataloader

  17. 17

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  18. 18

    상황에 맞는 메뉴 색상

  19. 19

    마우스 휠 JQuery 이벤트 핸들러에 대한 방향 가져 오기

  20. 20

    매개 변수에서 쿼리 객체를 선언하는 방법은 무엇입니까?

  21. 21

    Maven은 아이 프로젝트 대상 폴더를 청소하지

뜨겁다태그

보관