user113454 user113454 - 12 days ago 5
Java Question

Change the default padding character in Java printf?

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?

Answer

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(' ', '#'));