Gorgonzola45
Gorgonzola45

Reputation: 63

Combining / uniting two strings in Scala

What would be the best way to combine "__L_" and "_E__" to "_EL_" in Scala?

I don't want to use if and for commands.

Upvotes: 1

Views: 211

Answers (2)

Rüdiger Klaehn
Rüdiger Klaehn

Reputation: 12565

How about this:

def combine(xs: String, ys: String): String = 
  (xs zip ys).map {
    case ('_', y) => y
    case (x, _) => x 
  }.mkString("")

The only thing that is not really nice about this is how to get back from a collection (IndexedSeq[Char]) to a string. An alternative is to use the String constructor that takes an Array[Char]. That would probably be more efficient.

Note that zip will work for strings of different length, but the result will be the size of the shorter string. This may or may not be what you want.

Upvotes: 3

Odomontois
Odomontois

Reputation: 16308

def zipStrings(first: String,
               second: String,
               comb: (Char, Char) => String = (f, _) => f.toString, 
               placeholder: Char = '_') =
  first.zipAll(second, '_', '_').map {
  case (c, `placeholder`) => c
  case (`placeholder`, c) => c
  case (f, s) => comb(f, s)
}.mkString

that prioritises characters from first over second by default

zipStrings("__A", "X_CD") // yields "X_AD"

zipStrings("A__YY", "BXXXX", (f, s) => s"($f|$s)") // yields "(A|B)XX(Y|X)(Y|X)"

For you original strings:

zipStrings("L_", "_E")  // yield "LE"

zipStrings("--L-", "-E--", placeholder = '-') // yields "-EL-"

Upvotes: 2

Related Questions