使用 String.format() 打印空格
我该如何重写:
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
使用 String.format()
?
PS
我很确定这是可能的,但是 javadoc 有点混乱.
I'm pretty sure that this is possible but the javadoc is a bit confusing.
推荐答案
需要指定字段的最小宽度.
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");
这会给你 numberOfSpaces-5 个空格,然后是 Hello.如果您希望 Hello 出现在左侧,请在 numberOfSpaces 之前添加一个减号.
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.
相关文章