Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are strings terminated in C#?

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.!

like image 743
Naveen Kumar V Avatar asked Sep 25 '15 06:09

Naveen Kumar V


People also ask

How a string is terminated?

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.

What is the string terminator in C?

In C, strings are arrays of char's terminated with a '\0'.

Are all strings null-terminated in C?

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.

Why are strings in C null-terminated?

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.


1 Answers

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);  
like image 196
Richard Schneider Avatar answered Sep 30 '22 16:09

Richard Schneider