How to find the longest common prefix of two strings in Scala?

The imperative version can be simplified to

def longestCommonPrefix(s1:String, s2:String):String = {
  val maxSize = scala.math.min(s1.length, s2.length)
  var i:Int = 0;
  while ( i < maxSize && s1(i)== s2(i)) i += 1;
  s1.take(i);
}

Another recursive version.

def pref(s: String, t: String, out: String = ""): String = {
  if (s == "" || t == "" || s(0) != t(0)) out
  else pref(s.substring(1), t.substring(1), out + s(0))
}

It's over 10 times quicker than sjj's and over twice as fast as missingfaktor's. Java's substring is fast because String is immutable.


Recursive version:

def findCommonPrefix(s1 : String, s2 : String) : String = {
    def findCommonPrefixR(l1: List[Char], l2 : List[Char]) : List[Char] = {
        l1 match {
        case Nil => Nil
        case x::xs => if (l2 != Nil && l2.head == x) x :: findCommonPrefixR(xs, l2.tail) else Nil
        }
    }
    findCommonPrefixR(s1.toList, s2.toList).mkString
}

scala> "helloworld".zip("hellohell").takeWhile(Function.tupled(_ == _)).map(_._1).mkString
res130: String = hello