在 C#
中,您可以使用 para 2: {2}
指定用于格式化字符串的参数。这允许在任意位置多次使用参数。
有没有办法用标准 java 做到这一点?
最佳答案
是的。您可以定义参数的索引,参见 API 的 参数索引 部分.
例如:
// ┌ argument 3 (1-indexed)
// | ┌ type of String
// | | ┌ argument 2
// | | | ┌ type of decimal integer
// | | | | ┌ argument 1
// | | | | | ┌ type of decimal number (float)
// | | | | | |
System.out.printf("%3$s %2$d %1$f", 1.5f, 42, "foo");
输出
foo 42 1.500000
注意
以下成语都有相同的格式定义:
String#format
PrintStream#printf
Formatter#format
https://stackoverflow.com/questions/30099071/