Thursday, March 27, 2008

How to translate messages with strings inside

Often you need to translate strings that contain one or more variables that in the different languages stay in different positions of the string, so a solution like the following gives huge problems for those who have to translate:


out.println("h.netshape2flow TOOK " + timetaken + " sec");


That is why java gives us an alternative way to deal with this:


String pattern = "h.netshape2flow TOOK {0} sec";
Object[] args = new Object[]{timetaken};
pattern = MessageFormat.format(pattern, args);
out.println(pattern);


After struggling around for a while with messages in which the {0} wasn't substituted at all, I found a problem that Italian translator will have:

Problem: the apostrophe makes the messageformat go mad. So something like
"Non ho trovato l'attributo {0} nel piano {1}."
is tranformed to:
"Non ho trovato lattributo {0} nel piano {1}."

Solution: put every time 2 apostrophes.
"Non ho trovato l''attributo {0} nel piano {1}."
is tranformed to:
"Non ho trovato l'attributo bacino nel piano layer_bacino."

No comments: