This program throws ArrayIndexOutOfBoundException
.
string name = "Naveen";
int c = 0;
while( name[ c ] != '\0' ) {
c++;
}
Console.WriteLine("Length of string " + name + " is: " + c);
Why is it so?
If strings are not null-terminated. How strings are getting handled in C#?
How can I get the length without using string.Length
property?
I'm confused here.!
All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.
In C, strings are arrays of char's terminated with a '\0'.
C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose.
Because in C strings are just a sequence of characters accessed viua a pointer to the first character. There is no space in a pointer to store the length so you need some indication of where the end of the string is. In C it was decided that this would be indicated by a null character.
C# does not use NUL terminated strings as C and C++ does. You must use the Length
property of the string.
Console.WriteLine("Length of string " + name + " is: " + name.Length.ToString());
or by using formatters
Console.WriteLine("Length of string '{0}' is {1}.", name, name.Length);
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