How to convert a multiline Scala multiline String to an Array (or Seq)

Scala string FAQ: How do I convert a multiline String to an Array or Seq or List in Scala?

I was just working on a program to parse Apache access log records, and ran into this situation. Here’s the solution.

Given a multiline Scala string, like this:

  val data = """
124.30.7.162 - - [21/Jul/2009:02:48:11 -0700] "GET /foo HTTP/1.1" 200 16731 "http://www.google.co.in/search?hl=en&client=firefox-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 GTB5"
89.166.165.223 - - [21/Jul/2009:02:48:12 -0700] "GET /favicon.ico HTTP/1.1" 404 970 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11"
94.102.63.11 - - [21/Jul/2009:02:48:13 -0700] "GET / HTTP/1.1" 200 18209 "http://www.developer.com/bar" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"
"""

you can convert that string to an array like this:

val arr = data.split("\n")

In my case I also wanted/needed to weed out the empty strings, so I added a filter method call after split:

val arr = data.split("\n").filter(_ != "")

That’s all you need to do to convert a string to an array in Scala. If you want to be more specific and get a Seq, List, or other type as the result of these calls, just call one of the to* methods that are available on the resulting array (toSeq, toList, etc.).