I just had this problem in Scala where I wanted to concatenate two corresponding multiline strings into one final multiline string, such that the elements from the first string were always at the beginning of each line, and the lines from the second string were always second.
That is, given two Scala multiline strings like these:
val xs = """
|123
|456
|789
""".stripMargin.trim
val ys = """
|aaa
|bbb
|ccc
""".stripMargin.trim
I wanted to create a resulting multiline string like this:
123aaa
456bbb
789ccc
Solution
The solution to this takes just a few steps, and involves splitting the multiline strings into individual lines in a sequence, then zipping those two sequences together, and then using a function with map
to create the final multiline string.
Here’s the solution:
First, split the multiline strings into individual lines:
val xsLines = xs.split("\n")
val ysLines = ys.split("\n")
Next, zip the lines together with the zip
method that’s available on Scala sequence types:
val zippedLines = xsLines.zip(ysLines)
Next, concatenate that result:
val combinedLines = zippedLines.map { case (x, y) => x + y }
Then convert that result back into a single multiline string:
val result = combinedLines.mkString("\n")
and then print the result to verify it:
println(result)
Seeing the results
To see how that solution works, here is the line-by-line solution and results in the Scala REPL:
scala> val xsLines = xs.split("\n")
| val ysLines = ys.split("\n")
val xsLines: Array[String] = Array(123, 456, 789)
val ysLines: Array[String] = Array(aaa, bbb, ccc)
scala> val zippedLines = xsLines.zip(ysLines)
val zippedLines: Array[(String, String)] =
Array((123,aaa), (456,bbb), (789,ccc))
scala> val combinedLines = zippedLines.map { case (x, y) => x + y }
val combinedLines: Array[String] =
Array(123aaa, 456bbb, 789ccc)
scala> val result = combinedLines.mkString("\n")
val result: String =
123aaa
456bbb
789ccc
Although the REPL doesn’t currently show strings or multiline strings very well, the final solution is this multiline string:
"""123aaa
456bbb
789ccc"""
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
In summary, if you ever need to merge two multiline strings like this, essentially concatenating each line in the multiline strings, I hope this example and source code is helpful.