我有以下字符串:
友又相应的UTF-16表示(小端)是
CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
友 又"友又".Length返回4,因为字符串由CLR存储为4个2字节的字符。
我如何测量我的弦的长度?如何将其拆分成{ "友", "", "又" }
发布于 2013-01-02 08:18:11
作为documented
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());https://stackoverflow.com/questions/14115503
复制相似问题