Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...