更改Java printf中的默认填充字符? [英] Change the default padding character in Java printf?
本文介绍了更改Java printf中的默认填充字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们执行 System.out.printf(%10s,1);
默认情况下,将添加空格字符以填充10,右?有没有办法改变这个?
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?
我知道,你可以通过指定<$ c $来添加 0
c> 0 在 s
之前,但是 printf
是否支持其他任何内容?
I know, you can add 0
, by specifying 0
before the s
, but does printf
support anything else?
推荐答案
不。空间是硬编码的。以下是java.util.Formatter源码的片段:
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(' ', '#'));
这篇关于更改Java printf中的默认填充字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文