Java 使用 String.format() 打印空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1073787/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:09:39  来源:igfitidea点击:

print spaces with String.format()

javastringformat

提问by dfa

how I can rewrite this:

我如何重写这个:

for (int i = 0; i < numberOfSpaces; i++) {
    System.out.print(" ");
}

using String.format()?

使用String.format()?

PS

聚苯乙烯

I'm pretty sure that this is possible but the javadoc is a bit confusing.

我很确定这是可能的,但javadoc 有点令人困惑

采纳答案by pjp

You need to specify the minimum width of the field.

您需要指定字段的最小宽度。

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

为什么要生成一定长度的空格字符串。

If you want a column of this length with values then you can do:

如果您想要具有值的此长度的列,则可以执行以下操作:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

它为您提供 numberOfSpaces-5 个空格,后跟 Hello。如果您希望 Hello 出现在左侧,请在 numberOfSpaces 之前添加一个减号。

回答by willcodejavaforfood

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");