2

I am stuck with a problem dealing with displaying text in multiple languages. I achieve the language fairly easily by using resource bundles, but what made the problem more complicated is the requirement that certain computed values need to be injected into the text at runtime.

For example

You have earned 15 badges out of 39

where 15 and 39 are computed at runtime.

Initially I solved the problem by adding placeholder tag in the text like below

badgeMessage_en=You have earned ${earned_badge} badges out of ${total_badge}

and then using regular expression to replace them at runtime. But now the problem is we need to add support for other languages that does not have ${ in the charset. and I am stuck

what do I do? Is there a placeholder char thats universal in all charsets?

Thanks in advance for any help.

Srijit
  • 475
  • 7
  • 30
  • http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html – BalusC Dec 05 '13 at 19:50
  • Why make it more complicated than needed? [This question](http://stackoverflow.com/questions/3695230/how-to-use-java-string-format) and [the doc for String.format](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29) should do fine. – Jonathan Drapeau Dec 05 '13 at 19:54
  • 1
    The Java language uses Unicode as its character set (with UTF-16 for its String encoding) so `${` is always supported. Resource bundles in the default [properties](http://en.wikipedia.org/wiki/.properties) file format are always ISO-8859-1 with unsupported values encoded using escape sequences (e.g. € is represented as `\u20ac`.) The problem is in your localization process, your translation vendor, and/or the tools. – McDowell Dec 05 '13 at 20:03
  • @McDowell You are right.. the problem was really in the localization process. They were (dont know why) translating it into a non- utf-8 charset. I talked to them and they fixed and they could successfully embed placeholders. Thanks for all the help.. – Srijit Dec 06 '13 at 14:56

1 Answers1

4

You should have a look at Java's MessageFormat class:

String pattern = resourceBundle.getString(key); 
String message = MessageFormat.format(pattern, args);

MessageFormat automatically replaces placeholders between { and }

For example:

properties:
my.message=You have earned {0} badges out of {0}

Java:
String pattern = bundle.getString("my.message");
String message = MessageFormat.format(pattern, 15, 39); // You have earned 15 badges out of 39

MessageFormat also supports more sophisticated options like formatting dates, times or numbers.

micha
  • 47,774
  • 16
  • 73
  • 80