How to compare and convert emoji characters in C#

北城以北 提交于 2019-12-09 10:51:33

问题


I am trying to figure out how to check if a string contains a specfic emoji. For example, look at the following two emoji:

Bicyclist: http://unicode.org/emoji/charts/full-emoji-list.html#1f6b4

US Flag: http://unicode.org/emoji/charts/full-emoji-list.html#1f1fa_1f1f8

Bicyclist is U+1F6B4, and the US flag is U+1F1FA U+1F1F8.

However, the emoji to check for are provided to me in an array like this, with just the numerical value in strings:

var checkFor = new string[] {"1F6B4","1F1FA-1F1F8"};

How can I convert those array values into actual unicode characters and check to see if a string contains them?

I can get something working for the Bicyclist, but for the US flag I'm stumped.

For the Bicyclist, I'm doing the following:

const string comparisonStr = "..."; //some string containing text and emoji

var hexVal = Convert.ToInt32(checkFor[0], 16);
var strVal = Char.ConvertFromUtf32(hexVal);

//now I can successfully do the following check

var exists = comparisonStr.Contains(strVal);

But this will not work with the US Flag because of the multiple code points.


回答1:


You already got past the hard part. All you were missing is parsing the value in the array, and combining the 2 unicode characters before performing the check.

Here is a sample program that should work:

static void Main(string[] args)
{
    const string comparisonStr = "bicyclist: \U0001F6B4, and US flag: \U0001F1FA\U0001F1F8"; //some string containing text and emoji
    var checkFor = new string[] { "1F6B4", "1F1FA-1F1F8" };

    foreach (var searchStringInHex in checkFor)
    {
        string searchString = string.Join(string.Empty, searchStringInHex.Split('-')
                                                        .Select(hex => char.ConvertFromUtf32(Convert.ToInt32(hex, 16))));

        if (comparisonStr.Contains(searchString))
        {
            Console.WriteLine($"Found {searchStringInHex}!");
        }
    }
}


来源:https://stackoverflow.com/questions/32895131/how-to-compare-and-convert-emoji-characters-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!