1

So, I've just started learning C#, and to be honest — I have no idea what I'm doing. I'm trying to make a string reverse app, and iv'e come up with this code:

string input = Console.ReadLine();
char[] wordArray = input.ToCharArray();
for(int i = input.Length; i >= 0; --i)
{
    Console.Write(wordArray[i]);
}

I've checked a bunch of different tutorials and documentations, and as far as I can tell from most of them, this should work, but it doesn't.

Whenever I run the app, I type in the word I want to reverse, and the app crashes. It shows an error that say "Index was outside the bounds of the array". I found better ways to reverse strings online using Array.Reverse(), but i would still like to understand why this error occurred. Like I said before, I'm not quite sure what I'm doing, and I'll be happy if anyone can explain this in layman's terms.

2
  • 2
    start from input.Length-1 Commented May 15, 2017 at 16:04
  • 1
    for(int i = input.Length-1; i >= 0; --i) arrays indexes starts in 0 and goes to lenght -1 Commented May 15, 2017 at 16:05

3 Answers 3

4

Your mistake is here int i = input.Length;. Your array is starting from 0 index and the last element is on index input.Length-1. So when you start from input.Lenght you are going out of bounds.

Sign up to request clarification or add additional context in comments.

Comments

1

Your 'array' (a group of elements) contains each of the characters in your string.

Each of these elements can be accessed by its index, which starts at 0. So for the word word you would have:

0: 'w'
1: 'o'
2: 'r'
3: 'd'

The Length of this array is 4 - it has 4 elements - but you can see that the largest index isn't 4, it's 3.

Your loop counts from 4 down to 0 (as its Length is 4). When attempting to access the element with index 4, it throws the exception 'Index was outside the bounds of the array'.

The explanation as to how this works above should make this error message self-explanatory: 4 is outside the bounds of 0 to 3. You should start your loop from 3, which is input.Length - 1.

Comments

-1

Maybe

string s = "123";
            string r = "";
            foreach (char c in s) r = c + r;
            Console.WriteLine(r);
            Console.ReadKey();

1 Comment

OP says he knows better ways to reverse the string. What was asked was why the particular solution produced an error - this answer does not address the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.