Reputation: 914
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?
Upvotes: 4
Views: 2760
Reputation: 14572
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.
Upvotes: 4