The question was: “What’s the cleanest way to add variable size String of spaces?”
Here’s my snippet:
def pad = { what, repeat -> what * repeat }
(0..9).each {
println "${pad(' ', it)}Hello!"
}
This gives:
Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello!
This makes use of the fact that you can just multiply strings in Groovy.
Quite neat, IMHO!
Groovy has a built-in solution, which has slightly different behaviour:
(0..9).each {
println "hello".padLeft(it, '_')
}
Gives:
hello hello hello hello hello hello _hello __hello ___hello ____hello
Unsurprisingly, a version making use of Apache Commons Lang StringUtils behaves exactly the same way:
import static org.apache.commons.lang.StringUtils.*
(0..9).each {
println leftPad('hello', it, '_')
}
Just for completeness: there’s java.util.Formatter but unlike with C’s printf function, one cannot specify a field’s width via a variable.
