Library contents

Groovy String.getChars

Copy a range of UTF-16 units into a caller-provided character array.

A simple example

String.getChars

  1. Start with Characters a, b, c
  2. Do this Copy just the middle character
  3. Result b
Starting at b and copying one position leaves a and c outside the result.

Syntax

Groovy syntax
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Copy a scanner suffix

A scanner returns a compound code, but the printed field needs only its numeric or trailing portion. Use the input boundaries and destination capacity to copy the intended range without including the prefix.

Result42
Lesson.groovy
char[] digits = new char[2]
"B-42".getChars(2, 4, digits, 0)
println new String(digits)
Output
42

The selected range contains just the digits.

Advertisements

Fill a fixed label

A printer has a template with room reserved for a short code. Copy the text into the intended positions so the surrounding brackets or other fixed characters stay in place.

From the programchar[] tag = "[ ]".toCharArray()
Result[CS]
Lesson.groovy
char[] tag = "[  ]".toCharArray()
"CS".getChars(0, 2, tag, 1)
println new String(tag)
Output
[CS]

The destination offset leaves both brackets in place.

Read a parcel sorting code

The depot scans a parcel marked NC-17. Copy the last two characters into a clean buffer for a numeric display. What does the copied field contain?

GivenNC-17
Worked result17

What to watch for

The end offset is exclusive and the destination must have room for the entire range.

Documentation for String.getChars