Find the intersection of two lines in Scala order

I am trying to find the intersection of two lines in Scala order. I am new to Scala, but it seems to me that this should be single-line. I tried using both the map and foldLeft, and have not yet received the correct answer.

Given two lines, return a list of characters that will be the same in order. For example, "abcd", "acc" should return "a", and "abcd", "abc" should return "abc".

Here are two functions that I have tried so far

(str1 zip str2).map{ case(a, b) => if (a == b) a else ""}

and

(str1 zip str2).foldLeft(""){case(acc,n) => if (n._1 == n._2) acc+n._1.toString else ""}

I want to do something like this

(str1 zip str2).map{ case(a, b) => if (a == b) a else break}

but it does not work.

I know that I can do this with multiple lines and a for loop, but it looks like a single liner. Can anyone help?

thank

+4
4
(str1 zip str2).takeWhile( pair => pair._1 == pair._2).map( _._1).mkString

scala REPL:

scala> val str1 = "abcd"
str1: String = abcd

scala> val str2 = "abc"
str2: String = abc

scala> (str1 zip str2).takeWhile( pair => pair._1 == pair._2).map( _._1).mkString
res26: String = abc

,

scala> (str1 zip "acc").takeWhile( pair => pair._1 == pair._2).map( _._1).mkString
res27: String = a
+2

, :

 def lcp(str1:String, str2:String) = 
      (str1.inits.toSet intersect str2.inits.toSet).maxBy(_.length)
 lcp("abce", "abcd")                              //> res0: String = abc
 lcp("abcd", "bcd")                               //> res1: String = ""

( 1 2)

+1

Alternatively, to avoid fastening whole lines:

(s1, s2).zipped.takeWhile(Function.tupled(_ == _)).unzip._1.mkString
0
source

There he is:

scala> val (s1, s2) = ("abcd", "bcd")
s1: String = abcd
s2: String = bcd

scala> Iterator.iterate(s1)(_.init).find(s2.startsWith).get
res1: String = ""

scala> val (s1, s2) = ("abcd", "abc")
s1: String = abcd
s2: String = abc

scala> Iterator.iterate(s1)(_.init).find(s2.startsWith).get
res2: String = abc
0
source

All Articles