user113454 user113454 - 1 year ago 104
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
, by specifying
before the
, but does
support anything else?

Answer Source

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(' ');
    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(' ', '#'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download