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

后端 未结 4 1298
挽巷
挽巷 2021-01-13 05:04

How do I compare these two string :

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

another example

val a = \"go pro hero 6\"
         


        
4条回答
  •  梦谈多话
    2021-01-13 05:43

    Here's an approach using for/yield that turned out similar to @leo-c approach. A for is used to generate a sliding window of length i from words to return the original words and combinations.

    def matchPattern(a:String, b: String): Boolean =  {
      val words = a.split(" ")
    
      val combinations = words ++ (for(
        i <- (2 to words.size);
        acc <- words.sliding(i)
      ) yield acc).map(_.mkString)
    
      combinations.contains(b)
    } 
    

    Test cases:

    val a = "fit bit versa"
    val b = "fitbit"
    
    val c = "go pro hero 6"
    val d = "gopro"
    
    val e = "hero go pro  6"  
    val f = "gopro"
    
    //false
    val g = "vegan protein powder"
    val h = "vega"
    
    val i = "foo gopro bar"
    val j = "gopro"
    
    val k = "foo go pro hero bar"
    val l = "goprohero"
    
    scala> matchPattern(a,b) && matchPattern(c,d) && matchPattern(e,f) &&  !matchPattern(g,h) && matchPattern(i,j) && matchPattern(k,l) 
    
    res175: Boolean = true
    

提交回复
热议问题