System.IndexOutOfRangeException : 索引超出数组范围

Joh*_*ohn 0 c#

我有以下数组:

public string reArrange(string s)
{
    char[] array = s.ToCharArray();
    int length = array.Length;
    char[] arranged = new char[length];

    for (int i = 0; i < length; i++)
    {
        int newposition = length - i;
        arranged[newposition] = array[i];
    }

    return new string(arranged);
}
Run Code Online (Sandbox Code Playgroud)

但是上述方法会引发以下错误:

System.IndexOutOfRangeException: 索引超出数组范围。

那么可能有什么问题呢?

das*_*ght 5

i为零时,您访问索引处的数组,该数组newposition等于length; 这超出了数组的最后一个有效索引,即0through length-1

这将解决问题:

int newposition = length - i - 1;
Run Code Online (Sandbox Code Playgroud)