dipu
dipu

Reputation: 1340

How do you handle internationalization for "Your input 'xyz' is excellent!"

I would like to know what is the right way to handle internationalization for statements with runtime data added to it. For example 1) Your input "xyz" is excellent! 2) You were "4 years" old when you switched from "Barney and Freinds" to "Spongebob" shows.

The double quoted values are user data obtained or calculated at run time. My platforms are primarily Java/Android. A right solution for Western languages are preferred over weaker universal one.

Upvotes: 9

Views: 1746

Answers (3)

BalusC
BalusC

Reputation: 1109222

Java

To retrieve localized text (messages), use the java.util.ResourceBundle API. To format messages, use java.text.MessageFormat API.

Basically, first create a properties file like so:

key1 = Your input {0} is excellent!
key2 = You were {0} old when you switched from {1} to {2} shows.

The {n} things are placeholders for arguments as you can pass in by MessageFormat#format().

Then load it like so:

ResourceBundle bundle = ResourceBundle.getBundle("filename", Locale.ENGLISH);

Then to get the messages by key, do:

String key1 = bundle.getString("key1");
String key2 = bundle.getString("key2");

Then to format it, do:

String formattedKey1 = MessageFormat.format(key1, "xyz");
String formattedKey2 = MessageFormat.format(key2, "4 years", "Barney and Friends", "Spongebob");

See also:


Android

With regards to Android, the process is easier. You just have to put all those String messages in the res/values/strings.xml file. Then, you can create a version of that file in different languages, and place the file in a values folder that contains the language code. For instance, if you want to add Spanish support, you just have to create a folder called res/values-es/ and put the Spanish version of your strings.xml there. Android will automatically decide which file to use depending on the configuration of the handset.

See also:

Upvotes: 12

supercat
supercat

Reputation: 81227

I think one will probably have to define one's format string to include a "1-of-N" feature, preferably defined so as to make common cases easy (e.g. plurals). For example, define {0#string1/string2/string3} to output string1 if parameter 0 is zero or less, string2 if it's precisely 1, and string3 if it's greater than 1}. Then one could say "You have {0} {0#knives/knife/knives} in the drawer."

Upvotes: 0

Pontus Gagge
Pontus Gagge

Reputation: 17268

One non-technical consideration. Embedding free data inside English phrases isn't going to look very smooth in many cultures (including Western ones), where you need grammatical agreement on e.g. number, gender or case. A more telegraphic style usually helps (e.g. Excellent input: "xyz") -- then at least everybody gets the same level of clunkiness!

Upvotes: 3

Related Questions