Checking if values in List is part of String

前端 未结 2 1924
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 17:47

I have a string like this:

val a = \"some random test message\"

I have a list like this:

val keys = List(\"hi\",\"random\",         


        
相关标签:
2条回答
  • 2020-12-13 17:57

    Something like this?

    keys.exists(a.contains(_)) 
    

    Or even more idiomatically

    keys.exists(a.contains)
    
    0 讨论(0)
  • 2020-12-13 18:13

    The simple case is to test substring containment (as remarked in rarry's answer), e.g.

    keys.exists(a.contains(_)) 
    

    You didn't say whether you actually want to find whole word matches instead. Since rarry's answer assumed you didn't, here's an alternative that assumes you do.

    val a = "some random test message"
    val words = a.split(" ")
    val keys = Set("hi","random","test") // could be a List (see below)
    words.exists(keys contains _)
    

    Bear in mind that the list of keys is only efficient for small lists. With a list, the contains method typically scans the entire list linearly until it finds a match or reaches the end.

    For larger numbers of items, a set is not only preferable, but also is a more true representation of the information. Sets are typically optimised via hashcodes etc and therefore need less linear searching - or none at all.

    0 讨论(0)
提交回复
热议问题