简体   繁体   中英

Getting “Index was outside the bounds of the array” exception and I'm not sure why

public string[] ReverseString(string input)
{
    int startPos = 0;
    int stringLength = input.Length;

    string text = input;
    string[] inputArr = new string[stringLength];       
    string[] outputArr = new string[stringLength];      

    for (int index = 0; index < stringLength; index++)
    {
        inputArr[index] = text.Substring(startPos, 1);  
        ++startPos;
    }

    int outputIndex = 0;
    for (int index = stringLength; index > 0; index--)
    {
        outputArr[outputIndex] = inputArr[index];
        ++outputIndex;
    }
    return outputArr;
}

At this line:

outputArr[outputIndex] = inputArr[index];

The compiler is giving me an error saying:

"Index was outside the bounds of the array."

why? It seems to loop through the other array just fine but as soon as it touches this line it gives me that error.

Off-by-one mistake. This loop:

for (int index = stringLength; index > 0; index--)

The range of index is stringLength to 1 , while it should be stringLength - 1 to 0 . Change it to:

for (int index = stringLength - 1; index >= 0; index--)

The problem is that in your second loop, you are skipping 0 with the index.

outputArr[outputIndex] = inputArr[index];

To fix it, you should change the

inputArr[index]

to

inputArr[index - 1] .

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