Java Stringformatter可以重用参数吗?
我正在使用Java Stringformatter可以重用参数吗?,java,string,Java,String,我正在使用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") 作为凯皮尔斯答案的补充: 当您开始对一个参数进行编号时,必须对所有参数进行编号,否则结果将
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")
作为凯皮尔斯答案的补充: 当您开始对一个参数进行编号时,必须对所有参数进行编号,否则结果将不符合预期
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!"
这是行不通的。(但不会抛出任何错误,因此这可能会被忽略。)
String.format(“%s FOO%Funfact:我今天刚在谷歌上搜索了这个,然后又回到了我4年前的问题:)
String.format("Hello %1$s! What a %s %1$s!", "world", "wonderful");
// "Hello world! What a world world!"
String.format("%s FOO %<s %<s", "test")