我必须为 String.format 中的每个相同参数指定一个变量吗?

String hello = "Hello";


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


hello hello hello hello hello hello

在对 format 方法的调用中,hello变量需要重复多次吗? 还是有一个简写版本,可以让您指定一次应用到所有 %s标记的参数?

91961 次浏览

来自 那些文件:

  • 常规类型、字符类型和数值类型的格式说明符具有以下语法:

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

可选的 参数 _ 索引是一个十进制整数,指示参数在参数列表中的位置。第一个参数由 "1$"引用,第二个参数由 "2$"引用,等等。

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

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

例如:

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

结果为 hello hello hello hello

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

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

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

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

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

为了可读性和调试而添加空间。一旦格式显示正确,就可以在文本编辑器中删除空格:

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

你需要使用下面的索引参数 %[argument_index$]:

String hello = "Hello";
String.format("%1$s %1$s %1$s %1$s %1$s %1$s", hello);

结果: Hello Hello Hello Hello Hello Hello