Java Reference
In-Depth Information
Here's an example that checks strings to see if they are palindromes: that is, if they are the
same forward and backward. To check for palindromes you first need to remove any punc-
tuation and ignore case before reversing the string:
def palindromes = '''
Able was I ere I saw Elba
Madam, in Eden, I'm Adam
Sex at noon taxes
Flee to me, remote elf!
Doc, note: I dissent. A fast never prevents a fatness. I diet on cod.
'''
palindromes. eachLine {
String str = it.trim().replaceAll( /\W/ ,'').toLowerCase()
assert str. reverse () == str
}
Once again, a little Groovy code packs a lot of power. The method eachLine has been
added to the String class to break multiline strings at line breaks. It takes a closure as
an argument. In this case, no dummy variables were used in the closure, so each string is
assigned to the default variable called it .
The it variable
In a closure, if no dummy name is specified the term it is used by default.
The trim method is applied to the line to remove any leading and trailing spaces. Then
the replaceAll method is used to replace all non-word characters with an empty string.
Finally, the string is converted to lowercase.
The assert test uses another method added by Groovy to String , called reverse . Java
has a reverse method in StringBuffer , but not String . Groovy adds the re-
verse method to String for convenience.
Groovy adds lots of methods to the Java standard libraries. Collectively these are known
as the Groovy JDK and are one of the best features of Groovy. The Groovy documentation
includes GroovyDocs for both the Groovy standard library and the Groovy JDK.
Search WWH ::




Custom Search