Search code examples
c#string-length

Can i determine string length in c# doing something like this?


Out of curiosity I am trying to determine string length without using properties or methods, this is something that works in C, but still kind of new to this concept of \0.

From what I understood, and I am talking about C, this character is something that is automatically put after setting value to some string, so that it could be determined how much space is needed for storage, but how does this works in C#?

string str = "someText";
int lenght = 0;
while (str[lenght]!='\0')
{
    lenght++;
}
Console.WriteLine(str);
Console.WriteLine("String lenght is : "+ lenght);
Console.ReadLine();

Solution

  • Consider a string as an abstract sequence of characters. There are multiple ways to implement such sequence in a computer library. Here are some examples:

    • Null-terminated - A sequence of characters is terminated with a special character value '\0'. C uses this representation.
    • Character-terminated - This is similar to null-terminated, but a different special character is used. This representation is rare these days.
    • Length-prefixed - First few bytes of the string are used to store its length. Pascal used this representation.
    • Length-and-Character Array - This representation stores a string as a structure with an array of characters, and stores the length in a separate area.

    Mixed representations are also possible, such as storing null-terminated string inside a length-and-array representation.

    C# uses a combination of length-prefixed and null-terminated strings, and also allows null characters to be embedded in the string. However, it does not mean that you could access null terminator or the length bytes, because, unlike C, C# performs bound checks, and throws an exception on an attempt to access past the end of the string.