I'm using String.format
to create a formatted string with arguments. Is it somehow possible to tell the formatter to reuse an argument multiple times?
String.format(%s FOO %s %s, "test"); //desired output: "test FOO test 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")
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With