Search

Dark theme | Light theme

December 11, 2009

Groovy Goodness: Formatted Strings with sprintf

Groovy adds the sprintf() method to the Object class. This means we can use the method in all of the classes, because it is defined at the top of the hierarchy. The sprintf() method uses the Java Formatter syntax to format values. We get a String as a result from the method.


assert 'Groovy is cool!' == sprintf( '%2$s %3$s %1$s', ['cool!', 'Groovy', 'is'])
assert '00042' == sprintf('%05d', 42)