If we do System.out.printf("%10s", "1");
by default, the space characters will be added to fill in 10, right? Is there a way to change this?
I know, you can add 0
, by specifying 0
before the s
, but does printf
support anything else?
If we do System.out.printf("%10s", "1");
by default, the space characters will be added to fill in 10, right? Is there a way to change this?
I know, you can add 0
, by specifying 0
before the s
, but does printf
support anything else?
Nope. Space is hard-coded. Here's the snippet of java.util.Formatter source even:
private String justify(String s) {
if (width == -1)
return s;
StringBuilder sb = new StringBuilder();
boolean pad = f.contains(Flags.LEFT_JUSTIFY);
int sp = width - s.length();
if (!pad)
for (int i = 0; i < sp; i++) sb.append(' ');
sb.append(s);
if (pad)
for (int i = 0; i < sp; i++) sb.append(' ');
return sb.toString();
}
If you're looking to get a different padding you could do a post-format replace or something similar:
System.out.print(String.format("%10s", "1").replace(' ', '#'));
You can use any number, like:
System.out.printf("%77s", "1");
You can do more formatting by using format method, like:
System.out.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d");
output: d c b a