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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
