6

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?

user113454
  • 2,083
  • 7
  • 26
  • 33
  • 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);` – Jesper Apr 03 '12 at 17:01

2 Answers2

9

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(' ', '#'));
ɲeuroburɳ
  • 6,594
  • 3
  • 21
  • 20
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

Guillermo
  • 15
  • 1
  • 6
  • That will print 76 spaces and a digit 1, which is not what user1064918 was asking for. – Jesper Apr 03 '12 at 16:59
  • 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. – user113454 Apr 03 '12 at 17:01