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();
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:
'\0'
. C uses this representation.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.