我有以下字符串:
友𠂇又
对应的UTF-16表示(little-endian)是
CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
友 𠂇 又
"友𠂇又".Length
返回 4,因为 CLR 将字符串存储为 4 个 2 字节字符。
如何测量绳子的长度?如何将其拆分为 { "友", "𠂇", "又"}
?
最佳答案
作为documented :
The
Length
property returns the number ofChar
objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than oneChar
. Use theSystem.Globalization.StringInfo
class to work with each Unicode character instead of each Char.
获取长度:
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());
关于c# - 测量包含宽字符的字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14115503/