C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Array: The split def returns an array of strings. This has 3 elements. We call println on the three elements in a for-loop.
ForScala program that uses split
// The string we want to split.
val line = "brick,cement,concrete"
// Split on each comma.
val result = line.split(',')
// Array length.
println(result.length)
// Print all elements in array.
for (v <- result) {
println(v)
}
Output
3
brick
cement
concrete
Here: We call split and pass an Array argument. The elements are the characters we want to split on (the delimiters).
Result: The various delimiters are handled correctly by split. The alphabetical strings are returned in the array.
Scala program that uses split with multiple delimiters
// This has several delimiters.
val codes = "abc;def,ghi:jkl"
// Use an Array argument to split on multiple delimiters.
val result = codes.split(Array(';', ',', ':'))
// Print result length.
println(result.length)
// Display all elements in the array.
result.foreach(println(_))
Output
4
abc
def
ghi
jkl
Scala program that uses substring delimiter
// Strings are separated with two-char delimiters.
val equipment = "keyboard; mouse; screen"
// Split on substring.
val result = equipment.split("; ")
result.foreach(println(_))
Output
keyboard
mouse
screen
Result: The empty string between delimiters in the "items" string is ignored. The two surrounding delimiters are combined.
Scala program that uses split with Regex
// This string has an empty item between delimiters.
val items = "box; ; table; chair"
// Use a Regex to split the string.
// ... Any number of spaces or semicolons is a delimiter.
val result = items.split("[; ]+")
// Print our results.
// ... No empty elements are present.
for (r <- result) {
println(r)
}
Output
box
table
chair