使用 String.format() 打印空格 [英] print spaces with String.format()

查看:54
本文介绍了使用 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.

这篇关于使用 String.format() 打印空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆