如果你在String.format中多次获得相同的参数怎么样?

Car*_*rey 124 java string string-formatting

String hello = "Hello";

String.format("%s %s %s %s %s %s", hello, hello, hello, hello, hello, hello);

hello hello hello hello hello hello 
Run Code Online (Sandbox Code Playgroud)

hello变量是否需要在对format方法的调用中重复多次,或者是否有一个简写版本,允许您指定一次应用于所有%s标记的参数?

Ign*_*ams 240

来自文档:

  • 通用,字符和数字类型的格式说明符具有以下语法:

        %[argument_index$][flags][width][.precision]conversion
    
    Run Code Online (Sandbox Code Playgroud)

    可选的argument_index是十进制整数,表示参数列表中参数的位置.第一个参数引用"1$",第二个引用"2$",等等.

String.format("%1$s %1$s %1$s %1$s %1$s %1$s", hello);
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 53

另一种选择是使用相对索引:格式说明符引用与最后一个格式说明符相同的参数.

例如:

String.format("%s %<s %<s %<s", "hello")
Run Code Online (Sandbox Code Playgroud)

结果hello hello hello hello.


Ahm*_*rdi 11

您需要使用索引参数%[argument_index$],如下所示:

String hello = "Hello";
String.format("%1$s %1$s %1$s %1$s %1$s %1$s", hello);
Run Code Online (Sandbox Code Playgroud)

结果: hello hello hello hello hello hello


Eri*_*nil 6

重用参数的一种常见情况String.format是使用分隔符(例如,";"对于 CSV 或控制台的制表符)。

System.out.println(String.format("%s %2$s %s %2$s %s %n", "a", ";", "b", "c"));
// "a ; ; ; b"
Run Code Online (Sandbox Code Playgroud)

这不是所需的输出。"c"没有出现在任何地方。

您需要首先使用分隔符(with ),并且仅在出现以下情况时%s使用参数索引( ):%2$s

System.out.println(String.format("%s %s %s %2$s %s %n", "a", ";", "b", "c"));
//  "a ; b ; c"
Run Code Online (Sandbox Code Playgroud)

添加空格是为了可读性和调试。一旦格式看起来正确,就可以在文本编辑器中删除空格:

System.out.println(String.format("%s%s%s%2$s%s%n", "a", ";", "b", "c"));
// "a;b;c"
Run Code Online (Sandbox Code Playgroud)