Start learning free

LESSON 64 OF 677 · STRINGS I

String Split 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 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