I would like to know how the String.Length
can count the characters number.
If possible, a simple algorithm would be nice to explain it.
It doesn't. The number of characters is stored as a field (m_stringLength
, if it matters); .Length
simply returns this value. In .NET, strings are not typically nul-terminated or similar. The more interesting question is "where is the string data stored" - which is complex; the string
type is an exception to the usual rule, and the objects themselves have variable size; the character data is directly inside the string
object (it is not the case that the string
type has a pointer or reference to the character data; it is the character data, plus a length field).
SystemString.Length
does not count characters, it stores the length.
There are two general ways of storing strings - characters+length, and characters+terminator. In .NET the first approach is used; in other languages, such as C, the second approach is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With