Groovy String.subSequence
Return part of a string through the CharSequence interface.
A simple example
String.subSequence
- Start with "abc"
- Do this Take the first two characters
- Result "ab"
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.groovyRead 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.
CharSequence prefix = "BUS-8".subSequence(0, 3)
println prefix
BUS
The prefix can be passed to an API accepting CharSequence.
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.
println "B:42".subSequence(2, 4)
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?
What to watch for
This uses the same UTF-16 bounds as substring. The declared return type is CharSequence.