我String.format用来创建带参数的格式化字符串.是否有可能告诉格式化程序多次重用一个参数?
String.format(%s FOO %s %s, "test"); //desired output: "test FOO test test"
Run Code Online (Sandbox Code Playgroud)
Kep*_*pil 38
是的,您可以使用说明$符.前面的数字$表示参数号,从1开始:
String.format("%1$s FOO %1$s %1$s", "test")
Run Code Online (Sandbox Code Playgroud)
作为对Keppils答案的补充:开始为其中一个参数编号时,必须对所有参数都编号,否则结果将达不到预期。
String.format("Hello %1$s! What a %2$s %1$s!", "world", "wonderful");
// "Hello world! What a wonderful world!"
Run Code Online (Sandbox Code Playgroud)
会工作。而
String.format("Hello %1$s! What a %s %1$s!", "world", "wonderful");
// "Hello world! What a world world!"
Run Code Online (Sandbox Code Playgroud)
将无法正常工作。(但是不会引发任何错误,因此可能不会引起注意。)