Groovy String.chars
Stream the UTF-16 units of a string as nonnegative int values.
A simple example
String.chars
- Start with "AB"
- Do this Read the two UTF-16 units
- Result 65, 66
Syntax
public IntStream chars()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCount digits on a ticket
A ticket identifier mixes digits with letters and punctuation. Count only the digit positions needed for the report instead of treating the entire printed label as one numeric value.
println "T-482".chars().filter { n -> n >= 48 && n <= 57 }.count()
3
The numeric filter accepts ASCII digit units.
Measure one reaction in UTF-16
A ticket includes a symbol outside the basic multilingual plane. Inspect its UTF-16 representation before using the string length as a count of what a reader sees on the screen.
println "😀".chars().count()
2
One supplementary symbol is made of two units.
Read a parcel sorting code
The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.
What to watch for
Surrogate pairs produce two items. Use codePoints for a stream of complete Unicode code points.