You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将LINQ中char类型的y改为string类型以匹配Emoji?

C#中将Emoji作为字符串进行匹配的解决方案

原代码中直接遍历字符串得到的y是char类型,但很多Emoji(尤其是复杂表情)由UTF-16代理对或多个Unicode字符组成,用char无法完整表示单个Emoji,因此需要将每个Emoji转换为string类型再进行匹配。

方法一:使用StringInfo.GetTextElementEnumerator遍历完整文本元素

通过StringInfo.GetTextElementEnumerator可以遍历字符串中的每个完整文本元素(即单个Emoji,无论其由多少个char组成),每次迭代得到的结果是string类型的完整Emoji:

using System.Globalization;

string x = "😁🤨😭🔥🤣😁😈";
string targetEmoji = "😁";
var matchedList = new List<string>();

var elementEnumerator = StringInfo.GetTextElementEnumerator(x);
while (elementEnumerator.MoveNext())
{
    string currentEmoji = elementEnumerator.GetTextElement();
    if (currentEmoji == targetEmoji)
    {
        matchedList.Add(currentEmoji);
    }
}

Console.WriteLine(string.Join("", matchedList));

方法二:结合LINQ与StringInfo解析文本元素

如果偏好LINQ风格的写法,可以通过StringInfo.ParseCombiningCharacters获取每个文本元素的起始索引,再截取完整的Emoji字符串:

using System.Globalization;
using System.Linq;

string x = "😁🤨😭🔥🤣😁😈";
string targetEmoji = "😁";

var result = string.Join("", 
    StringInfo.ParseCombiningCharacters(x)
        .Select(index => x.Substring(index, StringInfo.GetNextTextElementLength(x, index)))
        .Where(emoji => emoji == targetEmoji)
);

Console.WriteLine(result);

关键说明

  • StringInfo类位于System.Globalization命名空间下,使用前需引入该命名空间。
  • 两种方法都能确保拿到的是完整的Emoji字符串,避免了char类型无法表示复杂Emoji的问题,匹配结果更准确。

内容的提问来源于stack exchange,提问作者MaKeSter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:00:01