在String.format()中选择参数

Daw*_*per 7 java formatting

C#您可以在其中指定用于格式化字符串的参数para 2: {2}.这允许在任意位置和多次使用参数.

有没有办法用标准的java做到这一点?

Men*_*ena 9

是.您可以定义参数的索引,请参阅APIArgument Index部分.

例如:

//                 ? 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");
Run Code Online (Sandbox Code Playgroud)

产量

foo 42 1.500000
Run Code Online (Sandbox Code Playgroud)

注意

以下习语都共享相同的格式定义:

  • String#format
  • PrintStream#printf
  • Formatter#format