Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a concept of '\0' in C#?

Tags:

string

c#

What I know is that in C++ and C \0 is used to end the string and then find the length of the string below method is used.

char[] arr = 'Welcome';
for( int i = 0; arr[i] != '\0'; i++){
  return i;
}

But for C# it does not seems to work. The code below works but basically catches the exception.

Update - Sorry for the confusion

  1. Is the above one just a method to find the length? By comparing it to '\0'

  2. Why does it not work C#? Is there a concept of '\0' in C# string str = "abc";

        int length = 0;
        try
        {
            length = 0;
            for (int i = 0; str[i] != '\0'; i++)
            {
                length++;
    
            }
        }
        catch (System.IndexOutOfRangeException)
        {
            Console.WriteLine(length);
            return;
        }
    

1 Answers

Strings aren't null-terminated in C# (at least visibly; I believe they are internally for the sake of interop, but the termination character occurs outside the bounds of the string itself). The concept of the character '\0' (U+0000) does exist, but it can occur anywhere within a string - there's nothing special about it.

That means that your code to find '\0' does not find the length of the string. (It would also be simpler just to call str.IndexOf('\0') which will return -1 if the string doesn't contain U+0000.)

For example you could have:

string str = "a\0b";

That is a string of length 3 - but your code would claim it had a length of 1.

Just use the Length property to determine the length of a string (in UTF-16 code units; not necessarily Unicode characters). The length is stored in the String object separately from the text data; the Length property accesses it directly rather than having to iterate over the data.

like image 179
Jon Skeet Avatar answered Oct 27 '25 10:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!