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

Clé*_*ent 7 c# unicode silverlight split

我有以下字符串:

??
Run Code Online (Sandbox Code Playgroud)

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

CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
  ?              ?
Run Code Online (Sandbox Code Playgroud)

"??".Length 返回4,因为CLR将字符串存储为4个2字节字符.

如何测量字符串的长度?我该如何拆分成{ "?", "", "?" }

GSe*_*erg 12

作为记载:

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


获取长度:

new System.Globalization.StringInfo("??").LengthInTextElements
Run Code Online (Sandbox Code Playgroud)

这里记录了获取每个Unicode字符,但是制作扩展方法要方便得多:

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

    while (en.MoveNext())
    {
        yield return en.GetTextElement();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

foreach (string segment in "??".TextElements())
{
    Console.WriteLine(segment);
}
Run Code Online (Sandbox Code Playgroud)

也可以用于长度:

Console.WriteLine("??".TextElements().Count());
Run Code Online (Sandbox Code Playgroud)