Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c# - Measuring the length of string containing wide characters

I have the following string:

友??又

The corresponding UTF-16 representation (little-endian) is

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

"友??又".Length returns 4, because the string is stored as 4 2-byte characters by the CLR.

How do I measure the length of my string? How do I split it into { "友", "??", "又" }?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As 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.


Getting length:

new System.Globalization.StringInfo("友??又").LengthInTextElements

Getting each Unicode character is documented here, but it's much more convenient to make an extension method:

public static IEnumerable<string> TextElements(this string s) {
    var en = System.Globalization.StringInfo.GetTextElementEnumerator(s);

    while (en.MoveNext())
    {
        yield return en.GetTextElement();
    }
}

and use it in a foreach or in a LINQ statement:

foreach (string segment in "友??又".TextElements())
{
    Console.WriteLine(segment);
}

which also can be used for length:

Console.WriteLine("友??又".TextElements().Count());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...