4

How can we set dynamic width and precision while formatting string? I know the following code works good, but how can we do it in a formatter way?

int len = 3;
String s = "Andy";
System.out.printf("%1$" + len + "." + len + "s%n", s);

Output:
And

I have tried this one. It didn't throw an error, but prints different value than expected. (It looks so messy, but I've tried to pass the 'len' to width and precision. That's it. :) )

System.out.printf("%2$%1$d.%1$ds%n", len, s);

Output:
%1$d.3s

Is it doable? If so, how can we get same output as the former one?

3
  • 1
    I would be modestly surprised if there were a better answer than your first one. Commented Mar 1, 2016 at 19:53
  • @Louis, I understand, but we generally use formatters to avoid String concatenations & more likely this looks like using the concatenation again. So I put it here to see if there is a better way. Commented Mar 1, 2016 at 20:00
  • 1
    I get that. I'm answering your question by saying "I'm pretty sure there isn't." Commented Mar 1, 2016 at 20:04

1 Answer 1

4

Unfortunatly, the formatter used in String.format read the String from left to right, so it doesn't notice the new flag generated. This would have been possible if it will read from right to left but the problem would have been with the varags since you can pass to many parameters to the methods.

So the only way to format something like

String.format("|%ds", 5, "foo")

to output

| foo

Would be to format twice, this would not be the most effecient but the most readable (and that not even really true ......)

So my solution looks like this

 String.format(String.format("|%%%ds", 5), "foo") //Here, I add a double %

the first formatter will return %5s that will be format again with the String.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.