Integrating phrase translation with String.Format
I have a phrase in English that looks like this: "I have {0} dogs and {1} cats". In code, I provide the data with a String.Format:
String.Format("I have {0} dogs and {1} cats", 1, 2)
So the output is this: "I have 1 dogs and 2 cats".
The problem that I'm trying to solve is the phrase "I have {0} dogs and {1} cats" nee开发者_如何学JAVAds to be translated in other languages.
In this Spanish translation example, the English phrase "I have {0} dogs and {1} cats" and the translated phrase "Tengo {0} perros y gatos {1}" are stored in a database.
If the user were to change "Tengo {0} perros y gatos {1}" to "Tengo {0} perros y gatos {3}", a System.FormatException will be thrown when I call String.Format("Tengo {0} perros y gatos {3}", 1, 2).
For now I'm trapping the format exception and it feels wrong. I'm looking for ideas on a better solution.
Before saving to the database, why not see if you String.Format throws? If so -- do not let the user save.
Just a simple idea that may solve the problem...
I would compare the translated phrase with the stored original phrase, to check if the number and types of placeholders are equal.
Parse the original English phrase, and check for placeholders, e.g. using a regex: /\{\d+\}/
(if you only use placeholders and no formatting). Check the matches, and compare them at edit-time to the translated string. This makes sure the application fails at a time the user can still correct it.
Well, I think your users shouldn't be able to change your translation string unless they know what they're doing. Usually, translators should be told that the {0}, {1} represents replacable parameters and should not be altered. All other people besides translators should have no access to these strings, IMHO.
There are two things you could do :
- Check that this does not happen when the translator saves the new translation, ie you could search for {XX} and see if the maximum number is different from the original translation. If so, don't save the new one.
- When displaying it, if there is an error like that, catch the exception and fall back to the default language that you know is correct.
You definitely need a validation function that can check the edited string in some way. Even in a different scheme that didn't use number position indicators there would still be opportunity for typos.
In terms of UI, after they finish their edit, you could show them a sample translation that actually fills in the parameterized values. This would serve the double purpose of validating their formatting string and giving them a visual double-check of how it will look in context.
Nightly unit tests can catch this problem.
Another idea:
Give this user a checker tool which the user can run after making changes.
精彩评论