从android中的国家名称获取国家/地区代码

Tri*_*tus 6 android country-codes

我知道有一种方法可以从国家/地区代码中获取国家/地区名称,但另一种方式是否也可能?到目前为止,我找不到将"荷兰"这样的字符串转换为"NL"的函数.如果可能,我如何获得国家/地区代码?

Vla*_*lad 7

public String getCountryCode(String countryName) {

    // Get all country codes in a string array.
    String[] isoCountryCodes = Locale.getISOCountries();
    Map<String, String> countryMap = new HashMap<>();
    Locale locale; 
    String name;

    // Iterate through all country codes:
    for (String code : isoCountryCodes) {
        // Create a locale using each country code
        locale = new Locale("", code);
        // Get country name for each code.
        name = locale.getDisplayCountry();
        // Map all country names and codes in key - value pairs.
        countryMap.put(name, code);
    }

    // Return the country code for the given country name using the map.
    // Here you will need some validation or better yet 
    // a list of countries to give to user to choose from.
    return countryMap.get(countryName); // "NL" for Netherlands.
}
Run Code Online (Sandbox Code Playgroud)

  • 每次调用方法创建`HashMap`都是非常糟糕的做法. (2认同)

Mur*_*göz 0

语言环境

Locale locale = new Locale("de");
locale.getCountry();
Run Code Online (Sandbox Code Playgroud)