newline

Scala: Convert a String with newline characters to a sequence/list of strings

If you ever need a Scala method/function to convert a string with newline characters in it to a sequence of strings (Seq[String]), here you go:

def convertStringWithNewlinesToSeq(s: String): Seq[String] =
    s.split("\n").toVector

You can convert the final result to a Vector, Seq, List, ArrayBuffer, Array, etc., but I prefer Vector. The Scala REPL demonstrates how it works:

scala> convertStringWithNewlinesToSeq("")
res0: Seq[String] = Vector("")

scala> convertStringWithNewlinesToSeq("foo")
res1: Seq[String] = Vector(foo)

scala> convertStringWithNewlinesToSeq("foo\nbar\nbaz")
res2: Seq[String] = Vector(foo, bar, baz)

scala> convertStringWithNewlinesToSeq("foo\nbar\nbaz\n\n")
res3: Seq[String] = Vector(foo, bar, baz)

How to create multiline strings in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 1.2, “How to Create Multiline Strings in Scala.”

Problem

You want to create multiline strings within your Scala source code, like you can with the “heredoc” syntax of other languages.

Solution

In Scala you create multiline strings by surrounding your text with three double quotes:

How to replace newline character with sed on Mac OS X (macOS)

I don’t have much time to explain this today, but ... if you want to see how to use the sed command on a Mac OS X (macOS) system to search for newline characters in the input pattern and replace them with something else in the replacement pattern, this example might point you in the right direction.

Using sed to add a newline on Mac OS X

As a quick note today, I have been converting parts of the Scala Cookbook from a plain text format to a Markdown format, and as part of that I needed to add some newline characters to add spacing to the document. This wouldn’t be bad if it was a few pages, but it’s hundreds of pages, so I decided to use the Unix sed command to do the work.

A Scala String chomp (or chop) function

Scala string FAQ: Does Scala have a String method like chomp or chop that you find in Perl?

If you're using Scala and want a string chomp or chop method that you're used to in languages like Perl to remove end of line characters, the stripLineEnd method will do what you want, as shown in the REPL:

A Perl array chomp example

Summary: How to use the Perl array chomp syntax to chomp every element in a Perl array.