Library contents

Groovy String.toCharArray

Create a new, editable array containing the string’s UTF-16 units.

A simple example

String.toCharArray

  1. Start with "AB"
  2. Do this Make a character array
  3. Result A, B
The two ASCII letters become two separate array elements.

Syntax

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

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

From the programchar[] tag = "A17".toCharArray()
ResultA*7
Lesson.groovy
char[] tag = "A17".toCharArray()
tag[1] = (char) 42
println new String(tag)
Output
A*7

The array can be edited before constructing the display copy.

Advertisements

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.

From the programString name = "Lab"
ResultLab
Lesson.groovy
String name = "Lab"
char[] data = name.toCharArray()
data[0] = (char) 67
println name
Output
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?

GivenNC-17
Worked result17

What to watch for

The array is a copy. For whole Unicode code points, use codePoints instead.

Documentation for String.toCharArray