Java 选择String.format()中的参数

Java 选择String.format()中的参数,java,formatting,Java,Formatting,在C#中,您可以使用para2:{2}指定格式化字符串使用的参数。这允许在任意位置多次使用参数 有没有办法用标准java实现这一点?有。您可以定义参数的索引,请参阅的参数索引部分 例如: // ┌ argument 3 (1-indexed) // | ┌ type of String // | | ┌ argument 2 // | | | ┌ type of d

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


有没有办法用标准java实现这一点?

有。您可以定义参数的索引,请参阅的参数索引部分

例如:

//                 ┌ 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#格式
  • PrintStream\printf
  • Formatter#format
  • 是的。从中可以看出,占位符的一般公式是

    %[argument_index$][flags][width][.precision]conversion
    
    我们对这部分感兴趣

    %[argument_index$][flags][width][.precision]conversion
     ^^^^^^^^^^^^^^^^^ 
    
    因此,您可以使用将
    x$
    添加到占位符中,其中
    x
    表示参数编号(从1开始索引),如

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

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

    我想你在找我

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

    使用:


    @Rahultripati,是的,我再次检查了,因此我移除了旗帜。@DeepikaRajani:-谢谢!我正在寻找您与MessageFormat共享的解决方案。谢谢
    MessageFormat.format("{1} {0}", "foo", "bar") //result: "bar foo"
    
    String.format("%1$s", object);