Can Stringformatter reuse arguments?

Just as a complement to Keppils answer: When you've started numbering one of your arguments, you have to number them all, or else the result will not be as expected.

String.format("Hello %1$s! What a %2$s %1$s!", "world", "wonderful");
// "Hello world! What a wonderful world!"

would work. While

String.format("Hello %1$s! What a %s %1$s!", "world", "wonderful");
// "Hello world! What a world world!"

would not work. (But does not throw any errors, so this might go unnoticed.)


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

Yes, you can use the $ specifier for this. The number preceding the $ indicates the argument number, starting from 1:

String.format("%1$s FOO %1$s %1$s", "test")

Tags:

Java

String