I have a collection of lines, like in this snippet:
def insertBeforeLine(text:String,whichLine:String,what:String) = {
val lines = text.lines
lines.foldLeft(ListBuffer[String]())((acumulator,element) => {
acumulator ++ { if(element == whichLine) Array(what,element) else Array(element) }
}).mkString("\n")
}
I am trying to prepend something before every line that’s equal to whichLine. Is there a better/cleaner way? For example if my input is:
line1
line2
line4
and I call my function like insertBeforeLine(input,"line4","line3") it will produce:
line1
line2
line3
line4
If you really have a string of lines (and you can include the end-of-line character, and it’s consistent), you can use replace from
java.lang.String:but if you want something more general, something like
is a compact and clear way to express it (at least to those who know how
flatMapworks).If you want something maximally efficient, then it’s a long ugly answer with lots of while loops and probably some byte array intermediates.