Reuse a parameter in String.format?

Carey picture Carey · Jul 31, 2011 · Viewed 67.2k times · Source
String hello = "Hello";

String.format("%s %s %s %s %s %s", hello, hello, hello, hello, hello, hello);

hello hello hello hello hello hello 

Does the hello variable need to be repeated multiple times in the call to the format method or is there a shorthand version that lets you specify the argument once to be applied to all of the %s tokens?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Jul 31, 2011

From the docs:

  • The format specifiers for general, character, and numeric types have the following syntax:

        %[argument_index$][flags][width][.precision]conversion
    

    The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

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