更改 Java printf 中的默认填充字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9997767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the default padding character in Java printf?
提问by user113454
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?
如果我们System.out.printf("%10s", "1");
默认这样做,空格字符将被添加以填充10,对吗?有没有办法改变这种情况?
I know, you can add 0
, by specifying 0
before the s
, but does printf
support anything else?
我知道,您可以0
通过0
在 之前指定来添加s
, 但是否printf
支持其他任何内容?
回答by ?eurobur?
Nope. Space is hard-coded. Here's the snippet of java.util.Formatter source even:
不。空间是硬编码的。这里甚至是 java.util.Formatter 源代码片段:
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(' ', '#'));
回答by random.learner
You can use any number, like:
您可以使用任何数字,例如:
System.out.printf("%77s", "1");
You can do more formatting by using format method, like:
您可以使用 format 方法进行更多格式化,例如:
System.out.format("%4s %3s %2s %1s", "a", "b", "c", "d");
output: d c b a
输出:dcba