为不同语言制作字符串的最佳方法是什么?我遇到了这个问题,我正在尝试显示诸如‘月’、‘月’、‘年’、‘年’之类的字符串。目前我正在学习3种我知道的语言:西班牙语,英语和波兰语。对于英语和西班牙语,这是直接的。但例如,在波兰语中,‘年’可以变成'lata‘(在数字2-4之后)或'lat’(在数字5之后)。我在考虑为它添加一个额外的字符串,并在其他语言中将其设为空。然而,这让我想到了其他我不知道的语言,它们可能会有更多的差异。在这种情况下,如果我正在考虑在未来添加更多的语言,哪种方法应该是最好的?
发布于 2010-06-29 05:41:08
听起来您想要一个ChoiceFormat
,或者至少通过MessageFormat
使用一个
public static void main(String... args) {
String[] formats = {
// NOTE - In a real app, you'd fetch the format strings from a language,
// file, not hard-code them in your program. Obviously.
"{0,number} {0,choice,0#years|1#year|1<years}", // english
"{0,number} {0,choice,0#años|1#año|1<años}", // spanish
"{0,number} {0,choice,1#[fewer than 2]|2#lata|4<lat}", // polish
"{0,number} år", // swedish - singular and plural forms look the same!
};
int[] years = {0, 1, 2, 3, 4, 5, 6};
for (int year : years) {
for (String format : formats) {
System.out.println(MessageFormat.format(format, year));
}
System.out.println();
}
}
在您的程序中,您当然会从字符串文件中获取format
字符串。
发布于 2010-07-02 00:48:42
感谢我得到的答案,我写了2个基于Android的解决方案。我使用的第一个是复数。乍一看检查Plurals文档/示例,您可能会认为在sources检查只适用于区域设置'cs‘的“quantity=”(对于2-4个复数)。对于其余的语言环境,只有“一个”和“另一个”是有效的。所以在你的strings.xml文件中:
<plurals name ="years">
<item quantity="one">1 year</item>
<item quantity="other"><xliff:g id="number">%d</xliff:g> years</item>
</plurals>
因此,对于波兰语,我会说:
<plurals name ="years">
<item quantity="one">1 rok</item>
<item quantity="other"><xliff:g id="number">%d</xliff:g> lat</item>
</plurals>
然后我会在我的代码上写:
int n = getYears(...);
if (Locale.getDefault().getLanguage().equalsIgnoreCase("pl") && n >= 2 && n <= 4) {
return getString(R.string.years_pl, n);
} else {
return getResources().getQuantityString(R.plurals.years, n, n);
}
在我的波兰语区域设置的strings.xml文件中,我会添加缺少的字符串:
<string name="years_pl"><xliff:g id="number">%d</xliff:g> lata</string>
我的第二个解决方案为英语、西班牙语和其他没有太多复数变化的语言提供了复数元素。然后,对于其他有这种变化的语言,我会使用ChoiceFormat。所以在我的代码中:
...
private static final int LANG_PL = 0;
// add more languages here if needed
...
String formats[] = {
"{0,number} {0,choice,1#" + getString(R.string.year_1) + "|2#" + getString(R.string.years_2_4) + "|4<" + getString(R.string.years_lots) +"}", // polish
// more to come
};
...
// Here I would add more for certain languages
if (Locale.getDefault().getLanguage().equalsIgnoreCase("pl")) {
return MessageFormat.format(formats[LANG_PL], n);
} else {
return getResources().getQuantityString(R.plurals.years, n, n);
}
我不知道这些方法是不是最好的方法,但就目前而言,或者在谷歌做出更好的东西之前,这对我来说是有效的。
发布于 2010-06-29 05:56:41
有一个内置的“复数”支持,但没有很好的文档记录。
提到了here,你可以在Browser sources中看到它。
https://stackoverflow.com/questions/3136288
复制相似问题