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

查看:218
本文介绍了用String.format()打印空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

使用 String.format()

$ b

我很确定这是可能的,但 javadoc有点混乱

解决方案

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

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

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

如果你想要一个长度为这个值的列,那么你可以这样做:

  String。格式(%+ numberOfSpaces +s,Hello); 

这给了你numberOfSpaces-5空格后跟Hello。如果您希望Hello出现在左侧,请在numberOfSpaces之前添加一个减号。


how I can rewrite this:

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

using String.format()?

PS

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"); 

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天全站免登陆