Search

Dark theme | Light theme

October 31, 2009

Groovy Goodness: Access Strings with Subscript Operator

Groovy adds a lot of support to the String class. The getAt method is added and that means we can use the subscript operator ([]) to access parts of a String.

def s = 'Accessing Strings in Groovy is easy.'

assert 'A' == s[0]
assert 'A' == s.getAt(0)
assert 'Groovy' == s[21..26]  // We can use ranges.
assert 'easy.' == s[s.indexOf('ea')..-1]

// We can also use each method on a String.
s[21..26].each { println "$it-" } // Output: G-r-o-o-v-y-