8

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?

1
  • Padding with 0 is only supported for numeric types. It will not work with s, but it will, for example, with d: System.out.printf("%010d", 1); Commented Apr 3, 2012 at 17:01

2 Answers 2

11

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(' ', '#'));
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

That will print 76 spaces and a digit 1, which is not what user1064918 was asking for.
Yes, @Jesper, I didn't mean the number of spaces. I meant the "character" to fill the empty space if the string is shorter than the specified length in the format.

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.