Daily Knowledge Drop
String.Length
does not always return a "true" accurate length of the string - instead, the StringInfo.LengthInTextElements
method should be used.
String Length
Generally, for most common string usage, the String.Length
will return the correct length of the string - the number of characters in the string object. However, the number of characters in the string object does not always correspond to the number of characters which reflect on the screen
.
For example:
Console.Write("This string '👍' has the length of: ");
Console.WriteLine("👍".Length);
The output of the above is:
This string '??' has the length of: 2
The terminal window is unable to render the 👍 emoji, so it is reflected as '??' - but this also gives insight into its length (two question marks, and no one). Even though 👍 reflects as one character when output, it actually consists of two characters in the string object
.
StringInfo LengthInTextElements
To get a more accurate string length, the StringInfo.LengthInTextElements
property can be used:
Console.Write("This string '👍' has the true length of: ");
Console.WriteLine(new StringInfo("👍").LengthInTextElements);
The output of the above is:
This string '??' has the length of: 1
The LengthInTextElements property will return the number of text elements displayed in the terminal.
Notes
If the length of the string is required for display purposes, and the string could contain "non-traditional" characters, such as emoji's - then the StringInfo.LengthInTextElements property should be used for more accurate results.
References
Getting the printable length of a string or character
Daily Drop 237: 18-01-2023
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.