How do I compare these two string :
val a = \"fit bit versa\"
val b = \"fitbit\"
another example
val a = \"go pro hero 6\"
I think this is a solution to your problem.
def matchPattern(a: String, b: String): Boolean =
a
.split("\\s+")
.tails
.flatMap(_.inits)
.exists(_.mkString("") == b)
This will check for any word or sequence of words in a
that exactly matches the word in b
. It will reject cases where b
is embedded in a longer word or sequence of words.
The split
call turns the string into a list of words.
The tails
call returns all the possible trailing sub-sequences of a list, and inits
returns all the leading sub-sequences. Combining the two generates all possible sub-sequences of the original list.
The exist
call joins the words together and compares them with the test word.
Note that tails
and inits
are lazy, so they will generate each solution to be tested in turn, and stop as soon as a solution is found. This is in contrast to the solutions using sliding
which create every possible combination before checking any of them.