How to Reverse a String in C# Using a For Loop?

In this C# tutorial, I have explained, how to reverse a string in C# using a for loop. I will show a complete example with the output.

Reverse a String in C# using a For Loop

Imagine you have a word, let’s say “HELLO”. If you were to write it backward, you’d get “OLLEH”. Essentially, reversing a string means you’re reading it from the end to the beginning.

Here is an example.

using System;

class Program
{
    static void Main()
    {
        string original = "HELLO";
        string reversed = ReverseString(original);

        Console.WriteLine($"Original String: {original}");
        Console.WriteLine($"Reversed String: {reversed}");
    }

    static string ReverseString(string str)
    {
        char[] charArray = str.ToCharArray(); // Convert string to character array
        int length = charArray.Length;
        char[] reversedArray = new char[length];

        for (int i = 0; i < length; i++)
        {
            reversedArray[length - 1 - i] = charArray[i];
        }

        return new string(reversedArray);
    }
}

Once you run the code, you can see the output below:

reverse a string in c# using for loop

Code Explanation:

Here is the complete code explanation.

  • Conversion to Character Array: Since strings in C# are immutable, it’s more convenient to convert the string to a character array using the ToCharArray() method.
char[] charArray = str.ToCharArray();
  • Initialize the Reversed Array: Create a new character array of the same length to hold the reversed characters.
char[] reversedArray = new char[length];
  • The For Loop: The idea here is to iterate over the charArray from the start to the end, but fill up the reversedArray from the end to the start. Hence, for each character in charArray, we calculate its corresponding position in the reversed array using the formula length - 1 - i.
for (int i = 0; i < length; i++)
{
    reversedArray[length - 1 - i] = charArray[i];
}
  • Convert Back to String: Once the characters are placed in the reversed order, convert the character array back to a string using the string constructor.
return new string(reversedArray);

This is the complete code to reverse a string in c# using for loop.

Conclusion

Reversing a string in C# using a for loop is a straightforward process. It’s essential to understand the importance of using a character array, as it offers more flexibility for such manipulations, given that strings are immutable in C#.

You may like the following tutorials: