Start learning free

LESSON 63 OF 348 · STRINGS I

String Split in Scala in Scala

Lesson

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 == ["hello", "world", "foo"]

val csv = "a,b,c"
val parts = csv.split(",")
// parts == ["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

    String Split in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free