Scala String.split
Split an ordinary record on commas to count its fields.
A simple example
String.split
- Start with a,b
- Do this Split at the comma
- Result a and b
object Lesson {
def main(args: Array[String]): Unit = {
val value = "a,b"
println(value.split(",", -1).length)
}
}
2
Syntax
value.split(",", -1).length
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonCount stops in a shuttle record
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "Gate,Lab,Hall"
println(value.split(",", -1).length)
}
}
3
Three nonempty stop fields are present.
Handle an express route
A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "Depot"
println(value.split(",", -1).length)
}
}
1
With no delimiter the complete route is one field.
Count a choir equipment list
A teacher receives one comma-separated line of items. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.
What to watch for
These examples use simple unquoted fields. Use a CSV reader for quoted values or embedded commas.