Sen*_*ess 2 functional-programming scala
我有一系列的行,就像在这个代码片段中一样:
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")
}
Run Code Online (Sandbox Code Playgroud)
我试图在每一行等于之前预先添加一些东西whichLine.有更好/更清洁的方式吗?例如,如果我的输入是:
line1
line2
line4
Run Code Online (Sandbox Code Playgroud)
我调用我的函数insertBeforeLine(input,"line4","line3")会产生:
line1
line2
line3
line4
Run Code Online (Sandbox Code Playgroud)
如果你真的有一串行(并且你可以包含行尾字符,并且它是一致的),你可以使用replace from java.lang.String:
text.replace(which,what+which)
Run Code Online (Sandbox Code Playgroud)
但如果你想要更通用的东西,比如
lines.flatMap(l => if (l==which) Seq(what,l) else Seq(l))
Run Code Online (Sandbox Code Playgroud)
是一种紧凑而清晰的表达方式(至少对于那些知道如何flatMap运作的人来说).
如果你想要一些最有效的东西,那么它是一个很长的丑陋的答案,有很多while循环,可能还有一些字节数组中间体.