Translate country name into other language

懵懂的女人 提交于 2019-12-11 05:39:41

问题


I searched for a solution, but I have not found any.

I have this kind of information:

String locale = "en_GB";
String country = "Japonia"; //It means Japan in polish

I need to translate the country name "Japonia" into language indicated in string locale, so "Japan". Is there any way to do it?


回答1:


Assuming you know both the input language and the desired output language, an alternative approach - iterate the Locale(s) on the system using Locale.getAvailableLocales(), test if the country name matches from the desired in Locale - if so display it in the desired output Locale using getDisplayCountry(Locale)

String country = "Japonia";
Locale outLocale = Locale.forLanguageTag("en_GB");
Locale inLocale = Locale.forLanguageTag("pl-PL");
for (Locale l : Locale.getAvailableLocales()) {
    if (l.getDisplayCountry(inLocale).equals(country)) {
        System.out.println(l.getDisplayCountry(outLocale));
        break;
    }
}

Outputs

Japan

And if you modify the outLocale like

Locale outLocale = Locale.forLanguageTag("es-SP");

you get

Japón



回答2:


(Answer based on comment by Elliott Frisch)

The Java Runtime Library doesn't have a translation API, but the Locale class can be used to get the name of any country in any language, as long as you know the ISO 3166 alpha-2 country code, and the ISO 639 alpha-2 or alpha-3 language code.

Example for country Japan:

Locale countryJapan = new Locale.Builder().setRegion("JP"/*Japan*/).build();
Locale langEnglish  = new Locale.Builder().setLanguage("en"/*English*/).build();
Locale langPolish   = new Locale.Builder().setLanguage("pl"/*Polish*/).build();
Locale langJapanese = new Locale.Builder().setLanguage("ja"/*Japanese*/).build();
Locale langItalian  = new Locale.Builder().setLanguage("it"/*Italian*/).build();
System.out.println(countryJapan.getDisplayCountry(langEnglish));
System.out.println(countryJapan.getDisplayCountry(langPolish));
System.out.println(countryJapan.getDisplayCountry(langJapanese));
System.out.println(countryJapan.getDisplayCountry(langItalian));

Output

Japan
Japonia
日本
Giappone



回答3:


Yes, you can use a translation API. Like Microsoft's or Google's.



来源:https://stackoverflow.com/questions/44190906/translate-country-name-into-other-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!