外观
c#获取emoji字符串文本的长度问题
c#使用length获取长度的问题
在c#中,普通字符串用length方法获取长度是没有任何问题的,当字符串中出现了特殊的字符串,比如emoji表情字符串,使用length方法会得到与我们想要的长度不符合的结果。看下以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
// 字符串
string str = "😀😄🌎️🎄";
// 使用length方法获取字符串长度
int len = str.Length;
// 向控制台打印长度
Console.WriteLine(len);
}
}
}控制台输出结果:9

c#使用StringInfo来获取emoji字符串长度
如果遇到以上情况,那么请使用StringInfo来获取长度,我们将上面代码改成如下:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
// 字符串
string str = "😀😄🌎️🎄";
// 实例化StringInfo
StringInfo stringInfo = new StringInfo(str);
// 使用StringInfo的 LengthInTextElements 方法获取长度
string len = stringInfo.LengthInTextElements.ToString();
// 向控制台打印长度
Console.WriteLine(len);
}
}
}控制台输出结果:4

以上的结果正是我们想要达到的效果。所以推荐有emoji等特殊字符串的时候,使用StringInfo中的LengthInTextElements方法来获取字符串长度。
