How to reverse string in C# using while loop?

In this C# tutorial explains, how to reverse a string in c# using a while loop with complete code with examples. I will show you, how to reverse a string in C# without using for loop.

Reverse a string in C# using a while loop

The logic behind this is like below:

  1. Start at the end of the string.
  2. Fetch one character at a time.
  3. Build a new string by appending each character.

Here is a complete code of how to reverse a string in C# using a while loop.

using System;

class Program
{
    public static string ReverseString(string str)
    {
        int index = str.Length - 1; // Start at the last character
        string reversed = string.Empty; // Initialize an empty string for reversed version

        while (index >= 0)
        {
            reversed += str[index]; // Append the character to the reversed string
            index--; // Move to the previous character
        }

        return reversed;
    }

    static void Main()
    {
        Console.WriteLine("Enter a string:");
        string input = Console.ReadLine();
        
        string reversed = ReverseString(input);
        
        Console.WriteLine($"Reversed string: {reversed}");
    }
}

You can see, I enter the input as “United States” and it provides the reverse string.

reverse string in c# using while loop

Here is the code explanation:

  1. The ReverseString method takes a string as an input.
  2. The index variable is initialized to the last position of the string.
  3. The reversed string starts as an empty string.
  4. The while loop continues as long as the index is non-negative (i.e., as long as we haven’t reached the beginning of the string).
  5. Inside the loop, we append the character at the current index position of the original string to the reversed string. Then, we decrement the index to move to the previous character.
  6. Finally, the reversed string is returned.

Conclusion

In this C# tutorial, I have explained with an example, how to reverse a string in C# using a while loop.

You may also like: