简体   繁体   English

带有多个参数的 Java string.format 整体宽度

[英]Java string.format overall width with multiple params

I'm trying to format a string using Java's String.format .我正在尝试使用 Java 的String.format格式化字符串。 I need to create a string like this: "<padding spaces> int1 / int2" .我需要创建一个这样的字符串: "<padding spaces> int1 / int2"

Right now I have the following format: " %1$d/%2$d10" or "%1$d10/%2$" (or just "%1$d/%2$d" , without the width setting) but this is not working correctly.现在我有以下格式: " %1$d/%2$d10""%1$d10/%2$" (或只是"%1$d/%2$d" ,没有宽度设置)但这不能正常工作。 I want to have the string aligned to the right, with empty spaces as padding for a total width of 10.我想让字符串向右对齐,用空格作为填充,总宽度为 10。

I'm using "%1$10.1f" elsewhere in my code, for a single float.我在我的代码中的其他地方使用了"%1$10.1f" ,作为一个浮点数。 The double integers need to be padded to the same width.双整数需要填充到相同的宽度。

I have googled my brains out, but am unable to find a way to pad the total string instead of the two individual integers.我已经用谷歌搜索了我的大脑,但我无法找到一种方法来填充总字符串而不是两个单独的整数。 Help would be appreciated!帮助将不胜感激!

Create the double integer string first using:首先使用以下方法创建双整数字符串:

int one = 1;
int two = 2;
String dints = String.format("%d / %d", one, two);

Then format the string dints with a width of 10:然后格式化宽度为 10 的字符串dints

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

Printing whatYouWant should output:打印whatYouWant应该输出:

     1 / 2

You can also do it in one call, at the cost of readability, for instance:您也可以在一次调用中完成,但代价是可读性,例如:

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

Or shorter:或更短:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM