简体   繁体   中英

Scala read file and split and modify each line

I'm new to Scala. I want to read lines from a text file and split and make changes to each lines and output them.

Here is what I got:

 val pre:String = " <value enum=\""
 val mid:String = "\" description=\""
 val sur:String = "\"/>"

 for(line<-Source.fromFile("files/ChargeNames").getLines){
    var array = line.split("\"")
    println(pre+array(1)+mid+array(3)+sur);
 }

It works but in a Object-Oriented programming way rather than a Functional programming way.

I want to get familiar with Scala so anyone who could change my codes in Functional programming way?

Thx.

One traversal and no additional memory

 Source
  .fromFile("files/ChargeNames")
  .getLines
  .map { line =>
    //do stuff with line like
    line.replace('a', 'b')
  }
  .foreach(println)

Or code which is a little bit faster, according to @ziggystar

Source
  .fromFile("files/ChargeNames")
  .getLines
  .foreach { line =>
    //do stuff with line like
    println(line.replace('a', 'b'))
  }
val ans = for (line <- Source.fromFile.getLines) yield (line.replace('a', 'b')
ans foreach println

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM