Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Stringformatter reuse arguments?

Tags:

java

string

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" 
like image 352
membersound Avatar asked Jan 24 '14 09:01

membersound


2 Answers

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") 
like image 194
Keppil Avatar answered Sep 19 '22 21:09

Keppil


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.)

like image 29
jonahe Avatar answered Sep 21 '22 21:09

jonahe