-4

I'm using StringBuilder to replace each character in a string by using an int that gets converted to a char. For some reason, the string builder throws an "Out of index error" even if the index is inside of the range.

I want to use I as the index but I changed it to array.Length just to make sure the index was in range.

string input = Console.ReadLine();

char[] array = input.ToCharArray();

int totalOffsetToRemove = array.Length + 44;

StringBuilder sb = new StringBuilder(input);

string result;

for (int i = array.Length; i > 0; i--)
{
    char c = Convert.ToChar(totalOffsetToRemove);                    
    sb[array.Length] = c;

    result = sb.ToString();                  
    Console.WriteLine(result);

    totalOffsetToRemove -= 2;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Albin
  • 7
  • 6
  • 4
    Because of zero indexing (count it out)! – ggorlen Mar 24 '19 at 00:40
  • 2
    `int i = array.Length` .... is out of range.... try `int i = array.Length - 1`! – JohnG Mar 24 '19 at 00:44
  • 1
    Because string lengths are also zero-indexed. Example: we can agree `"hello"` is length 5. `"hello"[0] => 'h'`.. `"hello"[4] => 'o'` .. `"hello"[5] => crash`. – ggorlen Mar 24 '19 at 00:44
  • 1
    You should also change `i > 0` ... to ... `i >= 0` ... or you will miss the first item in the array. – JohnG Mar 24 '19 at 00:47
  • 1
    Because arrays are zero-indexed. That means that if you have an array with length = 5, then the valid indexes are 0 through 4 (or better, 0 through length - 1). If you learn to use the debugger, you can figure out these sorts of issue yourself. – Ken White Mar 24 '19 at 00:47
  • `but didn't know .Length was 1 indexed` What do you mean by this? `Length` is the length of the entity, as per the docs. It matters not whether it is 1 indexed or 0 indexed or anything else - the `Length` is the length. – mjwills Mar 24 '19 at 03:18
  • 4
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – mjwills Mar 24 '19 at 03:19
  • 1
    Why would you use `for` loop instead of a `foreach` loop since you never use `i`.... – Erik Philips Mar 24 '19 at 04:19

1 Answers1

1

Indexes start with zero, so array[array.Length] is not valid and index is ranged from 0 to array.Length - 1.

change

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

to

for (int i = array.Length - 1; i >= 0; i--)
mjwills
  • 23,389
  • 6
  • 40
  • 63
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171