181
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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Carey
  • 1,811
  • 2
  • 12
  • 3

4 Answers4

335

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);
TylerH
  • 20,799
  • 66
  • 75
  • 101
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
89

Another option is to use relative indexing: The format specifier references the same argument as the last format specifier.

For example:

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

results in hello hello hello hello.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Daniel
  • 1,494
  • 9
  • 9
27

You need to use the index argument %[argument_index$] as the following:

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

Result: Hello Hello Hello Hello Hello Hello

Jbk
  • 11
  • 3
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
6

One common case for reusing an argument in String.format is with a separator (e.g. ";" for CSV or tab for console).

System.out.println(String.format("%s %2$s %s %2$s %s %n", "a", ";", "b", "c"));
// "a ; ; ; b"

This isn't the desired output. "c" doesn't appear anywhere.

You need to use the separator first (with %s) and only use the argument index (%2$s) for the following occurences :

System.out.println(String.format("%s %s %s %2$s %s %n", "a", ";", "b", "c"));
//  "a ; b ; c"

Spaces are added for readability and debugging. Once the format appears to be correct, spaces can be removed in the text editor:

System.out.println(String.format("%s%s%s%2$s%s%n", "a", ";", "b", "c"));
// "a;b;c"
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124