Java string.format具有多个参数的总宽度

时间:2017-01-16 21:29:30

标签: java printf string.format

我尝试使用Java String.format格式化字符串。 我需要创建一个这样的字符串:"<padding spaces> int1 / int2"

现在我有以下格式:" %1$d/%2$d10""%1$d10/%2$"(或仅"%1$d/%2$d",没有宽度设置)但这不能正常工作。我想让字符串向右对齐,空格为填充,总宽度为10。

我在我的代码中的其他位置使用"%1$10.1f"作为单个浮点数。双整数需要填充到相同的宽度。

我已经搜索了我的大脑,但无法找到填充总字符串而不是两个单独整数的方法。 帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

首先使用:

创建双整数字符串
int one = 1;
int two = 2;
String dints = String.format("%d / %d", one, two);

然后格式化宽度为10的字符串dints

String whatYouWant = String.format("%10s", dints);

打印whatYouWant应输出:

     1 / 2

您也可以在一次通话中执行此操作,但会牺牲可读性,例如:

String whatYouWant = String.format("%10s", String.format("%d / %d", one, two));

或更短:

String whatYouWant = String.format("%10s", one + " / " + two);