2011-07-13 26 views
2

元素的更好的方式我行的集合,就像這個片斷:備用/前面加上使用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") 
    } 

我想每一行是等於whichLine之前,預先考慮的東西。有更好的/更清潔的方式嗎?例如,如果我輸入的是:

line1 
line2 
line4 

,我喜歡叫我insertBeforeLine(input,"line4","line3")功能就會產生:

line1 
line2 
line3 
line4 

回答

5

如果你真的有線條的字符串(你可以包括最終OF-行字符,這是一致的),你可以使用從java.lang.String取代:

text.replace(which,what+which) 

但如果你想要更多的東西一般情況下,像

lines.flatMap(l => if (l==which) Seq(what,l) else Seq(l)) 

是一種簡潔明瞭的表達方式(至少對那些知道flatMap作品的人來說)。

如果你想要的東西效率最高,那麼它是一個很長的醜陋回答,有很多while循環和可能的一些字節數組中間體。