Strings
suggest changeRemarks
A .NET string (System.String) is a sequence of System.Char values, and each char is one UTF-16 code unit. That is not the same as a user-visible character.
A user-visible character is a grapheme, drawn as a glyph, and defined by one or more Unicode code points. Each code point is encoded as one or more code units. A single System.Char is therefore not always one grapheme:
- One grapheme, because of combining characters, may result in two or more code-points: à is composed by two code-points: U+0061 LATIN SMALL LETTER A and U+0300 COMBINING GRAVE ACCENT. This is the most common mistake because
"à".Length == 2while you may expect1. - The same letter can be one code point, U+00E0 LATIN SMALL LETTER A WITH GRAVE, or the two code points above.
"\u00e0" == "\u0061\u0300"is false:==is ordinal and does not normalize. They compare as equal afterString.Normalize(), or with a culture-sensitive comparison. TheirLengthvalues still differ. - A Unicode sequence may be composed or decomposed. The character 한 (U+D55C HAN) may be one code point (one UTF-16 code unit) or a decomposed sequence of the syllables ᄒ, ᅡ, and ᆫ. Ordinal
==does not treat those forms as equal; a normalized or linguistic comparison does. - One code-point may be encoded to more than one code-units: character 𠂊 U+2008A HAN CHARACTER is encoded as two
System.Char("\ud840\udc8a") even if it is just one code-point: UTF-16 encoding is not fixed size! This is a source of countless bugs (also serious security bugs), if for example your application applies a maximum length and blindly truncates string at that then you may create an invalid string. - Some languages have digraphs and trigraphs. In Czech, ch is its own letter (after h and before i). A culture-aware sort then orders fyzika before chemie.
There are many more issues in text handling. See How can I perform a Unicode-aware character-by-character comparison?.
For international text, enumerate text elements instead of char values. That avoids splitting a surrogate pair or a combining sequence:
public static class StringExtensions
{
public static IEnumerable<string> EnumerateCharacters(this string s)
{
if (s == null)
return Enumerable.Empty<string>();
var enumerator = StringInfo.GetTextElementEnumerator(s.Normalize());
while (enumerator.MoveNext())
yield return (string)enumerator.Value;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents