Hi,

I am quite new to C# and programming in general. I am working on an exercise which asked me to write a program that reverses a string. I could not solve this so I looked at the answer which is shown below:

static void Main(string[] args)
{
Console.WriteLine("Enter a string:");
string myString = Console.ReadLine();
string reversedString = "";
for (int index = myString.Length - 1; index >= 0; index--)
{
reversedString += myString[index];
}
Console.WriteLine("Reversed: {0}", reversedString);

It looks straightforward but I dont understand these lines below:

string reversedString = "";


In this case why is an empty string assigned to reversedString?

for (int index = myString.Length - 1; index >= 0; index--)


I understand this loop apart from the 'mystring.Length - 1' part.

reversedString += myString[index];


This bit of code caused the most confusion.

I would appreciate it if someone would help me towards understang this. Also, what is it that I would more practice on in order to make me understand this and similar problems?

Thanks in advance.

Edited 5 Years Ago by __avd: Added [code] tags.

The assigning of an empty string is so when the line where it adds the character to the string won't cause a null reference error (you can't add a character to a null).

The mystring.Length-1 is to get the index of the last character. Since indexes are zero based the last index is one less than the length of the string. For example, if we had the string "This is my string" it would have a length of 17, but the indexes would be from 0 to 16. reversedString += myString[index] is shorthand for saying reversedString = reversedString + myString[index] .


That said, this is bad code. Continually combining strings is wasteful, and they should have used StringBuilder. It's also a lot easier to reverse a string:

char arr = myString.ToCharArray();
Array.Reverse(arr);
myString = new String(arr);
Comments
Good explanation.

This is some other solution:

void ReversingMethod()
        {
            string str = "This is a string that needs to be reversed";
            Array array = str.Split(' ');
            Array.Reverse(array);
            str = null;
            for (int i = 0; i < array.Length; i++)
            {
                str += array.GetValue(i) + " ";
            }
            MessageBox.Show("This is a reversed string:\n" + str);
        }

This is obviously a homework assignment, but the OP has done some effort to refrase it in the proper way.:sad:

Edited 5 Years Ago by ddanbe: n/a

This article has been dead for over six months. Start a new discussion instead.