Library contents

Groovy String.chars

Stream the UTF-16 units of a string as nonnegative int values.

A simple example

String.chars

  1. Start with "AB"
  2. Do this Read the two UTF-16 units
  3. Result 65, 66
The integer values for the uppercase letters A and B are 65 and 66.

Syntax

Groovy 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.groovy

Count 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.

From the programprintln "T-482".chars().filter { n -> n >= 48 && n <= 57 }.count()
Result3
Lesson.groovy
println "T-482".chars().filter { n -> n >= 48 && n <= 57 }.count()
Output
3

The numeric filter accepts ASCII digit units.

Advertisements

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.

Result2
Lesson.groovy
println "😀".chars().count()
Output
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.

GivenNC-17
Worked result5

What to watch for

Surrogate pairs produce two items. Use codePoints for a stream of complete Unicode code points.

Documentation for String.chars