Search

Dark theme | Light theme

September 9, 2025

Groovy Goodness: Get Next And Previous Characters

Since Groovy 1.8.2 the next and previous methods are added to the Character class. When you invoke the method next on a char or Character instance the next character is returned. And when you use the previous method the previous character is returned.
Groovy 5 adds an overloaded version of the next and previous method that accepts an int argument. With this argument you can specify the number of characters to skip before returning the next or previous character. For example 'a'.next(2) return 'c' and 'c'.previous(2) returns 'a'.

In the following example the next and previous methods are used:

assert 'a'.next() == 'b'

// You can specify an integer argument since Groovy 5.
assert 'a'.next(1) == 'b'
assert 'a'.next(5) == 'f'

// The next method can also be applied
// to a String value where the last
// character is used to get the next character.
assert 'bot'.next(4) == 'box'

assert 'b'.previous() == 'a'

// You can specify an integer argument since Groovy 5.
assert 'f'.previous(5) == 'a'

// The previous method can also be applied
// to a String value where the last
// character is used to get the previous character.
assert 'blog'.previous(5) == 'blob'

Written with Groovy 5.0.0.