Java string.format 具有多个参数的总宽度
Java string.format overall width with multiple params
我正在尝试使用 Java 的 String.format
格式化字符串。
我需要创建一个这样的字符串:"<padding spaces> int1 / int2"
.
现在我有以下格式:" %1$d/%2$d10"
或 "%1$d10/%2$"
(或只是 "%1$d/%2$d"
,没有宽度设置)但这不能正常工作。我想让字符串右对齐,用空格作为填充,总宽度为 10。
我在代码的其他地方使用 "%1.1f"
作为单个浮点数。双精度整数需要填充到相同的宽度。
我用谷歌搜索了我的大脑,但无法找到一种方法来填充整个字符串而不是两个单独的整数。
帮助将不胜感激!
首先使用以下方法创建双整数字符串:
int one = 1;
int two = 2;
String dints = String.format("%d / %d", one, two);
然后格式化字符串dints
,宽度为10:
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);
我正在尝试使用 Java 的 String.format
格式化字符串。
我需要创建一个这样的字符串:"<padding spaces> int1 / int2"
.
现在我有以下格式:" %1$d/%2$d10"
或 "%1$d10/%2$"
(或只是 "%1$d/%2$d"
,没有宽度设置)但这不能正常工作。我想让字符串右对齐,用空格作为填充,总宽度为 10。
我在代码的其他地方使用 "%1.1f"
作为单个浮点数。双精度整数需要填充到相同的宽度。
我用谷歌搜索了我的大脑,但无法找到一种方法来填充整个字符串而不是两个单独的整数。 帮助将不胜感激!
首先使用以下方法创建双整数字符串:
int one = 1;
int two = 2;
String dints = String.format("%d / %d", one, two);
然后格式化字符串dints
,宽度为10:
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);