get country code from country name in android

前端 未结 5 1262
旧时难觅i
旧时难觅i 2021-01-05 09:52

I know there is a way to obtain the country name from a country code, but is it also possible the other way arround? I have found so far no function that converts a String l

5条回答
  •  萌比男神i
    2021-01-05 10:42

    I improved Vlad answer. Because initialize HashMap every time you access the method is very bad practice. Unless you initializing the map once. The edited answer:

    public String getCountryCode(String countryName) {
        String[] isoCountryCodes = Locale.getISOCountries();
        for (String code : isoCountryCodes) {
            Locale locale = new Locale("", code);
            if (countryName.equalsIgnoreCase(locale.getDisplayCountry())) {
               return code;
            }
        }
        return "";
    }
    

提交回复
热议问题