Groovy String.getChars
Copy a range of UTF-16 units into a caller-provided character array.
A simple example
String.getChars
- Start with Characters a, b, c
- Do this Copy just the middle character
- Result b
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.groovyCopy 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.
char[] digits = new char[2]
"B-42".getChars(2, 4, digits, 0)
println new String(digits)
42
The selected range contains just the digits.
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.
char[] tag = "[ ]".toCharArray()
"CS".getChars(0, 2, tag, 1)
println new String(tag)
[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?
What to watch for
The end offset is exclusive and the destination must have room for the entire range.