String hello = \"Hello\";
String.format(\"%s %s %s %s %s %s\", hello, hello, hello, hello, hello, hello);
hello hello hello hello hello hello
Do
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"