Groovy tokenize and split
Groovy tokenize skips empty tokens. Java String.split with a negative limit preserves both interior and trailing empty fields.
A simple example
tokenize and split
- Start with a,b
- Do this Split at the comma
- Result a and b
Syntax
line.tokenize(',') / line.split(',', -1)
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Choose how to handle empty columns
An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.
def line = 'A,,B,'
println line.tokenize(',')
def columns = line.split(',', -1)
println columns.size()
println '[' + columns.last() + ']'
[A, B] 4 []
The two approaches answer different questions. Counting present labels yields two, while inspecting all positions in a four-column record yields four.
Groovy documentation for tokenize and split
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.
Count a solo order
The stationery desk receives one item without a separator. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.