0

I have the following array:

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);
}

But the above method raises the following error:

System.IndexOutOfRangeException: Index was outside the bounds of the array.

So what might be wrong?

Scott Smith
  • 3,900
  • 2
  • 31
  • 63
John John
  • 1
  • 72
  • 238
  • 501

4 Answers4

5

When i is zero, you access the array at index newposition which equals length; that's one beyond the last valid index for the array, which is 0 through length-1.

This will fix the problem:

int newposition = length - i - 1;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Say the length is 10 characters. On the first iteration of your loop, newposition = 10 - 0 = 10. This index is out of the bounds of the arranged array.

Also, see this post about reversing a string. From that post...

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}
Community
  • 1
  • 1
TylerOhlsen
  • 5,485
  • 1
  • 24
  • 39
1

You are going to far,

for (int i = 0; i < length-1; i++)
Orn Kristjansson
  • 3,435
  • 4
  • 26
  • 40
1
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 - 1;
       arranged[newposition] = array[i];
    }
    return new string(arranged);
}
mlorbetske
  • 5,529
  • 2
  • 28
  • 40
  • 1
    but in this case i will not be able to reach the last elemnet in the array[] – John John Oct 19 '12 at 01:59
  • The last element in the array is at index `length - 1`. Let's say the array has a length of 3, at `i = 0`, `newposition = 3 - 0 - 1 = 2` (length - 1), at `i = 2` (length - 1), `newposition = 3 - 2 - 1 = 0` at `i = 1`, `newposition = 3 - 1 - 1 = 1`, covering all the valid indexes – mlorbetske Oct 19 '12 at 02:01
  • if the array lenght is 5 then using (i < length -1) i will never reach the array[4]!!! – John John Oct 19 '12 at 02:04
  • oops, typo, editing now, thanks – mlorbetske Oct 19 '12 at 02:04