c# - 测量包含宽字符的字符串的长度

标签 c# silverlight unicode split

我有以下字符串:

友𠂇又

对应的UTF-16表示(little-endian)是

CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
  友       𠂇       又

"友𠂇又".Length 返回 4,因为 CLR 将字符串存储为 4 个 2 字节字符。

如何测量绳子的长度?如何将其拆分为 { "友", "𠂇", "又"}

最佳答案

作为documented :

The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.


获取长度:

new System.Globalization.StringInfo("友𠂇又").LengthInTextElements

获取每个Unicode字符是documented here , 但做一个扩展方法更方便:

public static IEnumerable<string> TextElements(this string s) {
    var en = System.Globalization.StringInfo.GetTextElementEnumerator(s);

    while (en.MoveNext())
    {
        yield return en.GetTextElement();
    }
}

并在 foreach 或 LINQ 语句中使用它:

foreach (string segment in "友𠂇又".TextElements())
{
    Console.WriteLine(segment);
}

也可用于长度:

Console.WriteLine("友𠂇又".TextElements().Count());

关于c# - 测量包含宽字符的字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14115503/

相关文章:

unicode - 在 ColdFusion 中将字符串转换为 utf-8 unicode

unicode - vim:为什么 col() 返回字节,而不是列

python - 从 python 脚本中检查 python 版本,并基于它检查 if/else

c# - 在此 ASP.NET webforms 页面中以何种顺序执行哪些方法

html - 在哪里可以找到具有所见即所得的 Silverlight HTML 编辑器?

c# - 如何在 .NET Framework 4.7.2 中引用 System.Management.Automation?

silverlight - 使用MVVM模式选择Silverlight Treeview项

.net - 如何创建 Silverlight 3 主题?

javascript - 检测用户是否在新选项卡中打开链接并重定向到新网址

c# - C# 中的#include 指令