Library contents

Java 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

Java syntax
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
JDK 21 method signatures (1)
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Copy a parcel number into a print buffer

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.

From the programString parcel = "PK-482"
Result482
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String parcel = "PK-482";
        char[] digits = new char[3];
        parcel.getChars(3, 6, digits, 0);
        System.out.println(new String(digits));
    }
}
Output
482

Only the three numeric positions are copied.

Advertisements

Fill a badge template in place

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[] badge = "[ ]".toCharArray()
Result[LAB]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        char[] badge = "[   ]".toCharArray();
        "LAB".getChars(0, 3, badge, 1);
        System.out.println(new String(badge));
    }
}
Output
[LAB]

Destination offset one preserves both brackets.

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