gpt4 book ai didi

c# - 测量包含宽字符的字符串的长度

转载 作者:太空狗 更新时间:2023-10-29 20:05:23 27 4
gpt4 key购买 nike

我有以下字符串:

友𠂇又

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

CB 53 40 D8 87 DC C8 53
\___/ \_________/ \___/
友 𠂇 又

"友𠂇又".Length 返回 4,因为 CLR 将字符串存储为 4 个 2 字节字符。

如何测量绳子的长度?如何将其拆分为 { "友", "𠂇", "又"}

最佳答案

作为documented :

The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com