Визначення довжини рядка

C#:
Визначення довжини рядка

How to: (Як робити:)

string example = "Привіт, світ!";
int length = example.Length;

Console.WriteLine(length); // Outputs: 13
string emptyString = String.Empty;
int emptyLength = emptyString.Length;

Console.WriteLine(emptyLength); // Outputs: 0

Deep Dive (Занурення у глибину)

In C#, strings are immutable and represented by the System.String class. The Length property is integral to this class and returns the number of Char objects in the string, which is essentially the count of UTF-16 code units. Historically, as programming languages evolved, various methods to measure strings were developed, but in C#, .Length has been the go-to since its inception.

Other methods, like StringInfo.LengthInTextElements, can handle strings with combined characters (like emojis or accented characters) more accurately when counting user-perceived characters, as opposed to code units.

Under the hood, Length property is a simple and fast operation, retrieving a value pre-stored in the string object without actually iterating through it.

See Also (Дивись також)