How to convert two-letter country codes to flag emojis?
Asked Answered
S

2

11

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#.

Salpingitis answered 13/11, 2017 at 19:37 Comment(1)
If you want to convert the entire country name into a flag emoji, you can look at this article prototypemakers.medium.com/… – Huntley
M
11

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(); // πŸ‡«πŸ‡·
Misspeak answered 28/4, 2020 at 3:15 Comment(0)
R
3

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!

Rubellite answered 13/11, 2017 at 19:53 Comment(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#. – Salpingitis
Interesting! Luckily the answer still isn't too hard; I've edited my answer. – Rubellite

© 2022 - 2024 β€” McMap. All rights reserved.