测量包含宽字符的字符串的长度

本文关键字:字符串 测量 字符 包含宽 | 更新日期: 2023-09-27 17:50:26

我有以下字符串:

友  又

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

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

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

如何测量字符串的长度?如何将其拆分为{ "友", " ", "又" }

测量包含宽字符的字符串的长度

如文档所示:

Length属性返回本实例中Char对象的数量,而不是Unicode字符的数量。原因是一个Unicode字符可能由多个Char表示。使用System.Globalization.StringInfo类来处理每个Unicode字符而不是每个Char。


得到长度:

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

获取每个Unicode字符的文档在这里,但是创建一个扩展方法要方便得多:

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());