在String.format()中选择参数

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

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

是。 您可以定义参数的索引,请参阅API的Argument 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"); 

产量

 foo 42 1.500000 

注意

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

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

我想你正在搜索String.format()

使用指定的格式字符串和参数返回格式化字符串。

使用:

 String.format("%1$s", object); 

是。 从https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax我们可以看到占位符的通用公式是

 %[argument_index$][flags][width][.precision]conversion 

我们对这部分感兴趣

 %[argument_index$][flags][width][.precision]conversion ^^^^^^^^^^^^^^^^^ 

所以你可以通过在你的占位符中添加x$来实现它,其中x代表参数编号(索引自1)就像

 String.format("%2$s %1$s", "foo", "bar"); //returns `"bar foo"` // ^^ ^^ ^^^ ^^^ // | +-----+ | // | | // +-----------------+ 

顺便说一句:如果你想使用像{x}这样的格式,只需使用MessageFormat.format

 MessageFormat.format("{1} {0}", "foo", "bar")