Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a string with another where the one has space in between

How do I compare these two string :

val a = "fit bit versa"
val b = "fitbit"

another example

val a = "go pro hero 6"
val b = "gopro"

another example

val a = "hero go pro  6"
val b = "gopro"

another example

val a = "hero 6 go pro"
val b = "gopro"

I want to get "true" for the above comparisons but not here:

val a = "vegan protein powder"
val b = "vega"

This should be false.

Currently I am doing:

def matchPattern(a:String, b: String):String=
{
      val dd = a.split(" ")
      val result = dd.map(_.toLowerCase())
      if(result contains b.toLowerCase) true 
      else false
}

This works for last case but not the rest.

Any suggestion ?

like image 524
user3407267 Avatar asked Nov 16 '22 18:11

user3407267


1 Answers

Here's one approach using sliding(i), where i ranges from 2 to word-count in a, to assemble a list of all possible concatenated adjacent words. It is then checked to see whether b exactly matches any of the elements in the list, as shown below:

def matchPattern(a: String, b: String): Boolean = {
  val words = a.toLowerCase.split("\\s+")

  val concats = (2 to words.size).foldLeft(words)(
    (acc, i) => acc ++ words.sliding(i).map(_.mkString)
  )

  concats contains b.toLowerCase
}

matchPattern("Hero go Pro 6", "gopro")
// res1: Boolean = true

matchPattern("Hero go Pro 6", "gopro6")
// res2: Boolean = true

matchPattern("Vegan protein powder", "vega")
// res3: Boolean = false
like image 118
Leo C Avatar answered Dec 06 '22 16:12

Leo C