字符串格式化程序可以重用参数吗?
我正在使用创建带有参数的格式化字符串。是否有可能以某种方式告诉格式化程序多次重用一个参数?String.format
String.format(%s FOO %s %s, "test"); //desired output: "test FOO test test"
我正在使用创建带有参数的格式化字符串。是否有可能以某种方式告诉格式化程序多次重用一个参数?String.format
String.format(%s FOO %s %s, "test"); //desired output: "test FOO test test"
是的,您可以为此使用说明符。前面的数字表示参数编号,从 1 开始:$
$
String.format("%1$s FOO %1$s %1$s", "test")
就像对Keppils答案的补充:当你开始对你的一个论点进行编号时,你必须将它们全部编号,否则结果将不会像预期的那样。
String.format("Hello %1$s! What a %2$s %1$s!", "world", "wonderful");
// "Hello world! What a wonderful world!"
会工作。而
String.format("Hello %1$s! What a %s %1$s!", "world", "wonderful");
// "Hello world! What a world world!"
将不起作用。(但不会抛出任何错误,因此这可能会被忽视。