首页 > 解决方案 > 将国家名称转换为 ISO Alpha 2 国家代码

问题描述

我正在使用国家代码选择器库供用户选择国家。
我用国家名称(即:新加坡)存储了选定的项目。
现在我想将国家名称转换为 ISO Alpha 2 国家代码(即:sg)。

我正在使用语言环境,但它不起作用,我错过了什么?

public String getCountryCodeFromName(String countryName){
    Locale locale = new Locale("",countryName);
    String countryCode = locale.getCountry().toLowerCase();
    return countryCode;
}

标签: androidlocalecountry-codes

解决方案


Use This Function:-

public String getCountryCode(String countryName) {

    // Get all country codes in a string array.
    String[] isoCountryCodes = Locale.getISOCountries();
    String countryCode = "";
    // Iterate through all country codes:
    for (String code : isoCountryCodes) {
        // Create a locale using each country code
        Locale locale = new Locale("", code);
        // Get country name for each code.
        String name = locale.getDisplayCountry();
        if(name.equals(countryName))
          {
             countryCode = code;
             break;
          }
    }
    return countryCode;  
}

推荐阅读