Groovy String.toCharArray
Create a new, editable array containing the string’s UTF-16 units.
A simple example
String.toCharArray
- Start with "AB"
- Do this Make a character array
- Result A, B
Syntax
public char[] toCharArray()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCreate a masked badge copy
A badge preview hides one identifying character before it appears on a public screen. Modify a separate copy so the original badge data can still be used at the check-in desk.
char[] tag = "A17".toCharArray()
tag[1] = (char) 42
println new String(tag)
A*7
The array can be edited before constructing the display copy.
Keep the original course code
A preview changes one position in a badge or label while a master copy is still needed. Work out which value is mutable so editing the preview cannot alter the source used for the next print.
String name = "Lab"
char[] data = name.toCharArray()
data[0] = (char) 67
println name
Lab
String data is immutable.
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 array is a copy. For whole Unicode code points, use codePoints instead.