C# Program to Reverse a String with Output and Explanation
new string(input.Reverse().ToArray()) or by looping through the string backwards and building a new one.Examples
How to Think About It
Algorithm
Code
using System; using System.Linq; class Program { static void Main() { string input = "hello"; string reversed = new string(input.Reverse().ToArray()); Console.WriteLine(reversed); } }
Dry Run
Let's trace the input "hello" through the code that reverses it using the built-in Reverse method.
Input string
input = "hello"
Reverse characters
input.Reverse() produces sequence: 'o', 'l', 'l', 'e', 'h'
Convert to array
ToArray() creates char array ['o', 'l', 'l', 'e', 'h']
Create new string
new string(...) becomes "olleh"
Print output
Console prints: olleh
| Iteration | Character |
|---|---|
| 1 | o |
| 2 | l |
| 3 | l |
| 4 | e |
| 5 | h |
Why This Works
Step 1: Using Reverse() method
The Reverse() method returns characters from the string in reverse order as a sequence.
Step 2: Converting to array
We convert the reversed sequence to a character array with ToArray() because new string() needs an array.
Step 3: Creating new string
The new string() constructor builds a new string from the reversed characters, giving the reversed string.
Alternative Approaches
using System; class Program { static void Main() { string input = "hello"; string reversed = ""; for (int i = input.Length - 1; i >= 0; i--) { reversed += input[i]; } Console.WriteLine(reversed); } }
using System; using System.Text; class Program { static void Main() { string input = "hello"; var sb = new StringBuilder(); for (int i = input.Length - 1; i >= 0; i--) { sb.Append(input[i]); } Console.WriteLine(sb.ToString()); } }
Complexity: O(n) time, O(n) space
Time Complexity
The reversal requires visiting each character once, so it takes linear time proportional to the string length.
Space Complexity
A new string or array is created to hold reversed characters, so space grows linearly with input size.
Which Approach is Fastest?
Using Reverse() with ToArray() is concise and efficient; StringBuilder is better for very long strings when using loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Reverse() + ToArray() | O(n) | O(n) | Quick and readable for most cases |
| For loop with string concatenation | O(n²) | O(n) | Simple but slow for long strings |
| For loop with StringBuilder | O(n) | O(n) | Efficient for long strings with manual control |
input.Reverse().ToArray() with new string() for a quick and clean string reversal.