得到长度:
我有以下字符串:
友𠂇又
对应的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());