Format a message using MessageFormat.format () in Java

I saved some posts in the resource set. I am trying to format these messages as follows.

import java.text.MessageFormat; String text = MessageFormat.format("You're about to delete {0} rows.", 5); System.out.println(text); 

Assume that the first parameter ie the actual message is stored in a properties file that is somehow received.

The second parameter ie 5 is a dynamic value and should be placed in placeholder {0} , which does not occur. The next line prints,

You are about to delete lines {0}.

The placeholder is not replaced by the actual parameter.




This is the apostrophe here - You're . I tried to run away from him, as usual, like You\\'re , although this did not work. What changes are needed to make it work?

+40
java resourcebundle
Jul 10 '13 at 11:34 on
source share
5 answers

Add an extra apostrophe ' to the MessageFormat String template to display the character '

 String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5); ^ 

An apostrophe (aka single quote) in the MessageFormat template runs a quoted string and is not interpreted by itself. From javadoc

A single quote must be represented by double single quotes '' along the entire string.

String You\\'re equivalent to adding a backslash character to String , so the only difference is that You\re will be created, not Youre . (before applying the two-chamber solution '' )

+71
Jul 10 '13 at
source share

Just make sure you use the double apostrophe ('')

 String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5); System.out.println(text); 

Edit:

Inside String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, the pattern string "'{0}'" represents the string "{0}", not FormatElement ....

Any unsurpassed quote is considered closed at the end of this template. For example, the pattern string " " {0} "is considered as the pattern" " {0} .

Source http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html

+8
Jul 10 '13 at 12:02
source share

You need to use a double apostrophe instead of a single in "You''re", for example:

 String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5); System.out.println(text); 
+5
Jul 10 '13 at 11:38 on
source share

For anyone who has Android issues in the string.xml file, use \ '\' instead of a single quote.

+3
Jul 30 '14 at 9:49
source share

Using the apostrophe ' (Unicode: \u2019 ) instead of the single quote ' fixes the problem without duplication \' .

+1
Dec 14 '17 at 16:47
source share



All Articles