Valeriy K.
Valeriy K.

Reputation: 2904

How to format string with many placeholders and one value

I have a string template that can be changed and only one value which I want to insert in all placeholders. For example:

String str = "He%s%so, wor%sd";
String value = "L";

I know that I can do next:

String.format(str, value, value, value);

But what if this string changed, how I can format it without changing my code?

Upvotes: 6

Views: 2488

Answers (1)

yelliver
yelliver

Reputation: 5926

Just use %1$s instead of %s like this:

String str = "He%1$s%1$so, wor%1$sd";
String value = "L";
System.out.println(String.format(str, value)); //HeLLo, worLd

Actually, you can use %2, %3... to specific the index of param:

System.out.println(String.format("%2$s --- %1$s", "A", "B")); //B --- A

Upvotes: 9

Related Questions