【问题标题】:How to compare and convert emoji characters in C#如何在 C# 中比较和转换表情符号字符
【发布时间】:2015-12-29 22:52:56
【问题描述】:

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

骑车人: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);

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

【问题讨论】:

    标签: c# unicode string-matching emoji double-byte


    【解决方案1】:

    你已经克服了困难的部分。您所缺少的只是解析数组中的值,并在执行检查之前组合 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}!");
            }
        }
    }
    

    【讨论】:

    • 完美,谢谢。由于某种原因,组合字符让我绊倒了。
    • ?? 实际上是 U+1F1FA REGIONAL INDICATOR SYMBOL LETTER U 和 U+1F1F8 REGIONAL INDICATOR SYMBOL LETTER S,呈现为连字/组合对。在不支持标志的系统上,它通常会呈现为“US”。 amp-what.com/unicode/search/…
    猜你喜欢
    • 2019-03-06
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2020-10-22
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    相关资源
    最近更新 更多