How to split a string by newline in Scala

1 Answer

0 votes
object StringSplitterProgram {

  /**
   * Splits a multi-line string into a list of individual lines.
   * Automatically handles cross-platform line endings (Unix LF and Windows CRLF)
   * and strips trailing newline characters.
   * 
   * @param str The input multi-line string to be split.
   * @return A List[String] containing each individual line.
   */
  def splitByNewline(str: String): List[String] = {
    // Guard clause to handle null or empty inputs safely
    if (str == null || str.isEmpty) {
      List.empty
    } else {
      // linesIterator returns an Iterator[String] which is memory-efficient 
      // and natively handles both \n and \r\n endings without leaving trailing carriage returns.
      str.linesIterator.toList
    }
  }

  def main(args: Array[String]): Unit = {
    // Sample text containing mixed line endings (Unix LF, Windows CRLF, and an empty line)
    val multilineText = "Hello world!\nThis is line two.\r\n\nFinal line here."

    // Call the splitting function
    val resultLines = splitByNewline(multilineText)

    // Print out the parsed lines with their indices
    resultLines.zipWithIndex.foreach { case (line, index) =>
      println(s"Line ${index + 1}: '$line'")
    }
  }
}


/*
run:

Line 1: 'Hello world!'
Line 2: 'This is line two.'
Line 3: ''
Line 4: 'Final line here.'

*/

 



answered 10 hours ago by avibootz
...