Strings and Runes in Groovy
Groovy strings are similar to Java strings, but with some additional features. They are UTF-8 encoded by default and support interpolation. Groovy also has a concept similar to Go’s runes, which are called ‘characters’ in Groovy.
When you run this Groovy script, you’ll see output similar to the following:
This Groovy code demonstrates several concepts:
Groovy strings are UTF-8 encoded by default, allowing us to directly use Thai characters.
The
length()
method returns the number of bytes in the string, similar tolen(s)
in Go.We can iterate over the bytes of a string using the
bytes
property and print their hex values.The
size()
method returns the number of characters in the string, which is equivalent to the rune count in Go.We can use
eachWithIndex
to iterate over each character in the string along with its index.The
toCharArray()
method converts the string to a character array, which we can then iterate over.We define an
examineCharacter
method that checks for specific characters, similar to theexamineRune
function in the Go example.Groovy uses single quotes for character literals, just like Go uses single quotes for rune literals.
While Groovy doesn’t have a direct equivalent to Go’s runes, its character type serves a similar purpose in representing Unicode code points. The main difference is that Groovy characters are 16-bit, while Go runes are 32-bit integers.