Question

The code below prints the response variable preceded by spaces.

The number of spaces to be printed before the response variable is equivalent to the difference of the itemNumber and the examineeResponses.

Now, is it possible to pad the string with zero ("0") instead of spaces using String.format?

def converted = examineeResponses+String.format("%${itemNumber - 1}s", response)

Example using the above codes:

examineeResponses = '1' // String
itemNumber = 10 //int
response = '3' // String

Output:

"        3"

Desired output:

"000000003"
Was it helpful?

Solution

I believe you can do this, but it's a bit hard to understand your question:

int itemNumber = 10
String examineeResponses = '1'
char response = '3'

"$response".padLeft( itemNumber - examineeResponses.length(), '0' )

Though I suspect (you don't say) that you just want it printed itemNumbers characters wide. If this is the case, you just need:

"$response".padLeft( itemNumber, '0' )

And you don't need examineeResponses at all.

One of the bits I struggle with in your question is I don't know what examineeResponses.length() is supposed to do (other than throw an error). Another is I'm not sure that this is what you want to do ;-)

You can't zero pad Strings with String.format in Java or Groovy, you can only zero pad numerics

OTHER TIPS

Try something like this:

def formattedString = "blahblah.com?param=${param}&hash=${hash}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top