将国家/地区名称转换为 ISO Alpha 2 国家/地区代码



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

我正在使用区域设置,但它不起作用,我错过了什么?

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

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;  
}

相关内容

最新更新