Checking if the values ​​in the list are part of String

I have a line like this:

val a = "some random test message" 

I have a list like this:

 val keys = List("hi","random","test") 

Now I want to check if string a contains any values ​​from keys . How to do this using Scala's built-in library functions?

(I know a way to split a into List and then check with keys and then find a solution, but I'm looking for a way to more easily solve it using standard library functions.)

+30
string list scala scala-string
Apr 16 '13 at 8:10
source share
2 answers

Something like that?

 keys.exists(a.contains(_)) 

Or even more idiomatically

 keys.exists(a.contains) 
+50
Apr 16 '13 at
source share

A simple case is checking the contents of a substring (as indicated by rarry answer), e.g.

 keys.exists(a.contains(_)) 

You did not say if you really want to find whole words. Since the rarry answer suggested that you did not do this, here is an alternative that suggests that you do this.

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

Keep in mind that a key list is only effective for small lists. With a list, the contains method usually scans the entire list linearly until it finds a match or reaches the end.

For more elements, a set is not only preferable, but also a more true representation of information. Sets are typically optimized using hash codes, etc., and therefore they need less linear searching - or nothing at all.

+7
Apr 17 '13 at 18:29
source share



All Articles