简体   繁体   中英

Why we use -1 within a for Loop c#

I have code which checks if a word if a palindrome or not. Within the for loop there is a -1 value. Can someone explain to me why -1 is used after the name.Length in c#

 public static void Main()
    {

        string name = "Apple";
        string reverse = string.Empty;

        for (int i = name.Length - 1; i >= 0; i--)

        {
            reverse +=name[i];
        }

        if (name == reverse)
        {
            Console.WriteLine($"{name} is palindrome");
        }else
        {
            Console.WriteLine($"{name} is not palindrome");
        }

That's because whoever wrote the code, wanted to write:

reverse += name[i];

String operator [] takes values from 0 upto (string's length-1). If you pass length or more, you will get an exception. So, code's author had to ensure that i==Length won't be ever passed there. So it starts from Length-1 and counts downwards.

Also, note that the other bound of i is 0 ( >= , not > , so 0 is included), so the loop visits all values from 0 to length-1, so it visits all characters from the string. Job done.

However, it doesn't have to be written in that way. The only thing is to ensure that the string operator [] wont see values of of its range. Compare this loop, it's identical in its results:

    for (int i = name.Length; i >= 1; i--)
    {
        reverse += name[i-1];
    }

Note that I also changed 0 to 1.

Of course, it's also possible to write a loop with the same effects in a lot of other ways.

The first element in an array is at the index 0 ( array[0] ). Because the indexing starts at 0 instead of 1 it means that the final element in the array will be at index array.Length-1 .

If you had the word and then your array would look like:

name[0] = 'a'
name[1] = 'n'
name[2] = 'd'

the name.Length would equal 3. As you can see, there isn't an element at index 3 in the array so you need to subtract 1 from the length of the array to access the last element.

The for loop in your example starts with the last element in the array (using i as the index). If you tried to set i to i = name.Length then you would get an index out of bounds error because there isn't an element at the position name.Length .

String operator [] takes values from 0. The first element in an string is at the index 0, so we need to adjust by subtracting one.

For Example:

     string str = "test";
     int length = str.length; //Length of the str is 4. (0 to 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM