3

I have a template string

str = "Hello %s, your name is %s, %s 's born in 1990."

I want to format this string, as below: Hello Mr.P, your name is Mr.P, Mr.P 's born in 1990. I can do the following below:

String.format(str, "Mr.P","Mr.P","Mr.P");

to produce the above. Is there any other way to format the string without repeating same value n number of times as parameters

ThanhPhanLe
  • 1,315
  • 3
  • 14
  • 25
Prasanth
  • 507
  • 2
  • 10

3 Answers3

9

You can simply reference a specific argument:

String.format("Hello %1$s, your name is %1$s", "Mr.P")

% = Start of format string

1$ = First argument

s = Type String

Michael
  • 1,044
  • 5
  • 9
2

EDIT: It appears that String.format is smarter than I thought. Do the positional syntax given by @Michael

Use MessageFormat.

import java.text.MessageFormat;
...
    String str = "Hello {0}, your name is {0}, {0}'s born in 1990.";
    String str2 = MessageFormat.format(str, "Mr. P");
    System.out.println(str2);

Hello Mr. P, your name is Mr. P, Mr. Ps born in 1990.

This has the advantage of allowing you to create multiple placeholders and move them around in your pattern.

Docs: MessageFormat

Tad Harrison
  • 1,258
  • 5
  • 9
0
str = str.replace("%s", "Mr.P");