C# Understanding how to walk a string backwards

I'm taking a c# course and it has given me some code I copy and paste and some I do myself. Anyways, I don't understand in this for() loop why would we subtract 1 from the int i = target.Length property?

static string reverseString(string target)
        String result = "";

        // walk the target string backwards
        for (int i = target.Length - 1; i >= 0; i--)
            // add this letter to the result
            result += target[i];

        // return the result to the calling code
        return result;

2 answers

  • answered 2018-02-13 02:26 sjb-sjb

    It starts at Length - 1 because that is the last allowable index. Note it also includes index 0 (because of the ">= 0") which is the first allowable index. The increment is -1 so we consider decreasing values of the index instead of increasing ones.

  • answered 2018-02-13 02:26 Michael Hudson

    Take this example.

    string target = "ABC";
    // target can be thought of as an array of characters
    // target[0] holds 'A'
    // target[1] holds 'B'
    // target[2] holds 'C'
    int length = target.Length; 
    // length would be 3 because Length is the count of the chars
    // but if you were to try and get the value of target[3] you would get an error 
    // because target ends at [2] (index 2)

    So you need to start at .Length - 1 and work backwards to 0 (not 1).