如何在C#中比较和转换表情符号字符 [英] How to compare and convert emoji characters in C#

查看:292
本文介绍了如何在C#中比较和转换表情符号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何检查字符串是否包含特定表情符号。例如,查看以下两个表情符号:

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

自行车手: 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

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

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

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.

推荐答案

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

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

这篇关于如何在C#中比较和转换表情符号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆