Reputation: 505
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.
Upvotes: 2
Views: 1946
Reputation: 49582
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.
Upvotes: 4