问题

String hello = "Hello";

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

hello hello hello hello hello hello

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


#1 热门回答(206 赞)

Fromthe docs

常规,字符和数字类型的格式说明符具有以下语法:%[argument_index $] [flags] [width] [.precision]转换
 可选的argument_index是十进制整数,表示参数列表中参数的位置。第一个参数由"1 $"引用,第二个参数由"2 $"引用,等等。

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

#2 热门回答(32 赞)

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

例如:

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

结果在hello hello hello hello


#3 热门回答(2 赞)

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

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

这不是理想的输出."c"不会出现在任何地方。

你需要首先使用分隔符(with%s)并仅将参数index(%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"

原文链接