Start learning free

LESSON 64 OF 414 · STRINGS I

String Split in Scala: Breaking a String into an Array

Lesson Read the full explanation

In Scala, you can split a string into an array of substrings using split(). It takes a regular expression as the delimiter:

s.split(regex)   // splits using a regex delimiter

Here are some examples:

val sentence = "hello world foo"
val words = sentence.split(" ")
// words contains "hello", "world", "foo"

val csv = "a,b,c"
val parts = csv.split(",")
// parts contains "a", "b", "c"

You can loop through the resulting array:

for (w <- words) {
    println(w)
}

Assignment
Follow the Coding Tutorial and split sentence into a String array!


Hint
Use sentence.split(" ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · STRINGS I

    String Split in Scala, explained

    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".

    1. Choose the delimiter. The words are separated by single spaces, so the delimiter is " ".
    2. Call sentence.split(" ") and store it in a val named words. Scala infers the type Array[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 "" and a.
    • "".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" gives a and b,c.
    • "a, b ,c".split(",").map(_.trim) removes stray spaces around each piece.
    • Comparing two arrays with == compares references, not contents. Use sameElements or 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 an Array[String].
    • The delimiter is a regular expression, so escape special characters.
    • Trailing empty pieces are dropped by default.
    • Use mkString to print an array's contents.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free