10

I have ISO 3166-1 (alpha-2) country codes, which are two-letter codes, such as "US" and "NL". How do I get the corresponding flag emoji?

EDIT: Preferably I would like to do this without using an explicit mapping between country codes and their corresponding emojis. It has been done in JavaScript but I'm not sure how to do it in C#.

1

2 Answers 2

10

Solution:

public static string IsoCountryCodeToFlagEmoji(this string country)
{
    return string.Concat(country.ToUpper().Select(x => char.ConvertFromUtf32(x + 0x1F1A5)));
}

string gb = "gb".IsoCountryCodeToFlagEmoji(); // 🇬🇧
string fr = "fr".IsoCountryCodeToFlagEmoji(); // 🇫🇷
2

XXXXXXXX SKIP THIS SECTION WHICH CONTAINS MY ORIGINAL ANSWER XXXXXXXX

You will need to generate a cross-reference table or dictionary that allows you to look up the corresponding emoji. Luckily it looks like you've already found a great source for the information you need!

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can go here to find a chart of the appropriate unicode symbols for each letter. Basically, you just use the regional indicator symbol for each letter. For example, NZ would be U+1F1F3 (N) + U+1F1FF (Z). These two symbols are interpreted as the NZ flag if support is there for that emoji.

Because these letters are all contiguous, you can calculate the appropriate code for a given letter by using an offset from the normal upper case letters. You may have seen it in the code repository you referenced: it is 127397. Thus, 'A'+127397 is the regional indicator symbol for A.

Thanks for teaching me something new today, and good luck!

2
  • Damn, I should have mentioned this in my question: I know it can be done without a table. The Unicode character codes for emoji flags are set to specific codes that allows us to convert country codes directly. I found existing implementations of this in other languages (JavaScript, Swift) but I didn't understand them well enough to know how to do it in C#.
    – Rudey
    Nov 13, 2017 at 20:26
  • Interesting! Luckily the answer still isn't too hard; I've edited my answer.
    – Daniel
    Nov 13, 2017 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.