What split does
The split method cuts a string at every match of a delimiter and returns the pieces as an Array[String]. The delimiter is a regular expression, but plain characters such as a space or a comma mean themselves:
val sentence = "hello world foo"
val words = sentence.split(" ")
println(words.length) // 3
println(words(1)) // world
println("a,b,c".split(",").mkString("|")) // a|b|c
The pieces don't include the delimiter. split comes from Java's String, which is why the result is an Array and not a List. Arrays are indexed with parentheses, like words(1).
Looping over the pieces
for (w <- words) {
println(w)
}
hello
world
foo
Printing the array itself with println(words) doesn't show the contents, only a type tag and an identity code. Use words.mkString(", ") to print the elements, or words.toList if you prefer a List.
The exercise, step by step
The lesson gives you val sentence = "hello world foo".
- Choose the delimiter. The words are separated by single spaces, so the delimiter is
" ". - Call
sentence.split(" ")and store it in avalnamedwords. Scala infers the typeArray[String].
val sentence = "hello world foo"
val words = sentence.split(" ")
The array holds hello, world and foo.
Regular expression gotchas
Because the delimiter is a regular expression, characters like . and | are special and must be escaped with a double backslash:
println("a.b.c".split(".").length) // 0
println("a.b.c".split("\\.").mkString(",")) // a,b,c
println("a|b|c".split("\\|").mkString(",")) // a,b,c
The unescaped dot matches every character, so every piece is empty, and split then drops them, leaving an empty array.
Repeated delimiters
Two spaces in a row produce an empty string between them:
println("one two".split(" ").length) // 3
println("one two".split("\\s+").length) // 2
The pattern \\s+ means "one or more whitespace characters", so a run of spaces counts as one delimiter.
Empty strings at the ends
- Trailing empty pieces are removed:
"a,b,,".split(",")has two elements. A negative limit keeps them:"a,b,,".split(",", -1)has four. - A leading delimiter gives a leading empty piece:
",a".split(",")has the elements""anda. "".split(",")returns an array with one empty string, not an empty array.
Useful extras
s.split(",", 2)splits into at most two pieces, so"a,b,c"givesaandb,c."a, b ,c".split(",").map(_.trim)removes stray spaces around each piece.- Comparing two arrays with
==compares references, not contents. UsesameElementsor convert both to lists.
When to use split
Use split whenever one string holds several values joined by a separator: words in a sentence, fields in a comma-separated line, or parts of a path. After splitting, each piece is a normal string, so you can trim it, compare it or convert it. For example, "3,4,5".split(",").map(_.toInt) gives an Array[Int] with the numbers 3, 4 and 5.
If you know the separator is a fixed word or symbol and the string may be large, remember the cost: split compiles the delimiter as a pattern and allocates a new string for every piece. For the small strings in these lessons that doesn't matter.
Arrays versus lists
The result is an Array, which is mutable and has a fixed size: you can assign to words(0), but you can't add a fourth element. Most collection methods such as map, filter, length and mkString work on arrays directly. If you want an immutable collection, call toList or toVector on the result.
Key takeaways
s.split(delimiter)returns anArray[String].- The delimiter is a regular expression, so escape special characters.
- Trailing empty pieces are dropped by default.
- Use
mkStringto print an array's contents.
