测量包含宽字符的字符串的长度 [英] Measuring the length of string containing wide characters
本文介绍了测量包含宽字符的字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串:
友𠂇又
对应的UTF-16表示(小端)
CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
友 𠂇 又
"友𠂇又".Length
返回4,因为CLR将字符串存储为4个2字节字符。
如何测量我的弦的长度?如何将其拆分为{ "友", "𠂇", "又" }
?
推荐答案
ASdocumented:
Length
属性返回此实例中的Char
对象数,而不是Unicode字符数。原因是一个Unicode字符可能由多个Char
表示。使用System.Globalization.StringInfo
类处理每个Unicode字符,而不是每个字符。
获取长度:
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());
这篇关于测量包含宽字符的字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文