Count characters
suggest changeIf you need to count characters, for the reasons explained in the Remarks section of Strings, you can’t simply use the Length property. Length is the number of System.Char values, which are UTF-16 code units, not Unicode code points or graphemes. Correct code:
int length = text.EnumerateCharacters().Count();
A small optimization is to rewrite that walk specifically for counting:
public static class StringExtensions
{
public static int CountCharacters(this string text)
{
if (String.IsNullOrEmpty(text))
return 0;
int count = 0;
var enumerator = StringInfo.GetTextElementEnumerator(text);
while (enumerator.MoveNext())
++count;
return count;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents