print spaces with String.format()(使用 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() 打印空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 String.format() 打印空格
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
