0

I am trying to replace the {0} in a String with a value. The code I have written for it is:

String formattedText = MessageFormat.format("'{0}'", "1");
System.out.println(formattedText);

It is giving the output as : {0}

Please let me know what I am doing wrong.

VIBHOR GOYAL
  • 473
  • 1
  • 6
  • 22
  • No idea what your bigger use case is, but for simple cases, such as the example, maybe also consider using String.format instead. It seems easier to use for such straight forward formatting. – Frank Hopkins Feb 28 '20 at 10:34

4 Answers4

2

Try the below code :

 String formattedText = MessageFormat.format("''{0}''", "1");
        System.out.println(formattedText);

You can check this answer for more information.

Prog_G
  • 1,539
  • 1
  • 8
  • 22
0

You need to remove the single quotes from around the {0}. The format method sees that as a literal string.

mwarren
  • 759
  • 3
  • 6
0

It must be like

String formattedText = MessageFormat.format("{0}", "'1'");

Other wise '{}' is not considered to be a format place-holder.

Kris
  • 8,680
  • 4
  • 39
  • 67
0

Include double single quote should work:

MessageFormat.format("''{0}''", "1");

Or

You can use String.format:

String.format("'%s'", "1");

Vallabha Vamaravelli
  • 1,153
  • 1
  • 9
  • 15