The 英语国旗表情符号 https://emojipedia.org/flag-for-england/由 14 个字节的数据组成,组合后将呈现一个字符 -????????????????????????????
.
如果我有如下所示的代码:
var test = "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f";
Console.WriteLine(test);
Console.WriteLine(test.Length);
它将打印字符和数字14
。我不知何故希望它回来1
。在网上搜索答案时,我找到了这个解决方案:
var stringInfo = new System.Globalization.StringInfo(test);
Console.WriteLine(stringInfo.LengthInTextElements);
问题是,它反而打印7
。我猜它会将其解释为双字节 unicode 并且只给我一半的字节长度。看到这个点网小提琴 https://dotnetfiddle.net/au0GyX一个工作示例。
如何获得字符串所表示的字形数量?
这是用 Swift 编写的类似测试,在 OSX 上的 XCode 中运行,它显然按照我想要的方式工作,但我需要在 C# 中使用它。
在.NET 5中只需使用StringInfo.LengthInTextElements
。 .NET 早期版本中的此方法对这些表情符号有错误的行为。你可以看看这个blog https://www.meziantou.net/how-to-correctly-count-the-number-of-characters-of-a-string.htm.
在我的 C# Interactive(.NET Core 模式)中,我得到以下结果:
> Environment.Version
[5.0.7]
> var stringInfo = new System.Globalization.StringInfo("????????????????????????????");
. Console.WriteLine(stringInfo.LengthInTextElements);
1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)