Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use single quotes with MessageFormat

On my current project, we are using properties files for strings. Those strings are then "formatted" using MessageFormat. Unfortunately, MessagFormat has a handling of single quotes that becomes a bit of a hindrance in languages, such as French, which use a lot of apostrophes.

For instance, suppose we have this entry

login.userUnknown=User {0} does not exist

When this gets translated into French, we get:

login.userUnknown=L'utilisateur {0} n'existe pas

This, MessageFormat does not like...

And I, do not like the following, i.e. having to use double quotes:

login.userUnknown=L''utilisateur {0} n''existe pas

The reason I don't like it is that it causes spellchecking errors everywhere.

Question: I am looking for an alternative to the instruction below, an alternative that does not need doubling quotes but still uses positional placeholders ({0}, {1}…). Is there anything else that can I use?

MessageFormat.format(Messages.getString("login.userUnkown"), username);
like image 716
AbVog Avatar asked Jun 20 '16 11:06

AbVog


People also ask

How do you handle a single quote in Java?

In Java, \' denotes a single quotation mark (single quote) character, and \" denotes a double quotation mark (double quote) character. So, String s = "I\'m a human."; works well. However, String s = "I'm a human." does not make any compile errors, either. Likewise, char c = '\"'; works, but char c = '"'; also works.

What does MessageFormat format do in Java?

MessageFormat provides a means to produce concatenated messages in a language-neutral way. Use this to construct messages displayed for end users. MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.


1 Answers

No there is no other way as it is how we are supposed to do it according to the javadoc.

A single quote itself must be represented by doubled single quotes '' throughout a String

As workaround, what you could do is doing it programmatically using replace("'", "''") or for this particular use case you could use the apostrophe character instead which is it would be even more correct actually than using a single quote.

like image 145
Nicolas Filotto Avatar answered Oct 09 '22 10:10

Nicolas Filotto