如何在C#中比较和转换emoji字符

How to compare and convert emoji characters in C#

我想知道如何检查字符串是否包含特定的表情符号。例如,看下面两个表情符号:

自行车手:http://unicode.org/emoji/charts/full-emoji-list.html#1f6b4

美国国旗:http://unicode.org/emoji/charts/full-emoji-list.html#1f1fa_1f1f8

骑自行车的人是 U+1F6B4,美国国旗是 U+1F1FA U+1F1F8

但是,要检查的表情符号是在这样的数组中提供给我的,只有字符串中的数值:

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

如何将这些数组值转换为实际的 unicode 字符并检查字符串是否包含它们?

我可以为 Bicyclist 找到一些有用的东西,但是对于美国国旗我很难过。

对于骑自行车的人,我正在执行以下操作:

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

但这不适用于美国国旗,因为有多个代码点。

你已经通过了困难的部分。您所缺少的只是解析数组中的值,并在执行检查之前组合 2 个 unicode 字符。

这是一个应该可以运行的示例程序:

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}!");
        }
    }
}