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

后端 未结 4 1253
挽巷
挽巷 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:28

    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
    

提交回复
热议问题