Library contents

Groovy String.subSequence

Return part of a string through the CharSequence interface.

A simple example

String.subSequence

  1. Start with "abc"
  2. Do this Take the first two characters
  3. Result "ab"
The selected region includes a and b. The third character is outside it.

Syntax

Groovy syntax
public CharSequence subSequence(int beginIndex, int endIndex)
Run these examples in Groovy

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

groovy Lesson.groovy

Read the prefix of a booking

A booking service places a route prefix ahead of a reservation number. Extract that leading field so requests can be sent to the right service without altering the stored booking code.

From the programCharSequence prefix = "BUS-8".subSequence(0, 3)
ResultBUS
Lesson.groovy
CharSequence prefix = "BUS-8".subSequence(0, 3)
println prefix
Output
BUS

The prefix can be passed to an API accepting CharSequence.

Advertisements

Take the room number

A structured code contains a department, room or other routing field inside a longer label. Extract the exact portion needed by the receiving system and verify which boundary is excluded.

Result42
Lesson.groovy
println "B:42".subSequence(2, 4)
Output
42

The end offset is exclusive.

Read a parcel sorting code

The depot scans a parcel marked NC-17. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?

GivenNC-17
Worked resultNC

What to watch for

This uses the same UTF-16 bounds as substring. The declared return type is CharSequence.

Documentation for String.subSequence