C# Program to Reverse Words in a String
string.Split(' '), reversing the array with Array.Reverse(), and joining back with string.Join(' ', words).Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { string input = "C# is fun"; string[] words = input.Split(' '); Array.Reverse(words); string reversed = string.Join(' ', words); Console.WriteLine(reversed); } }
Dry Run
Let's trace the input "C# is fun" through the code.
Split the string
input.Split(' ') results in ["C#", "is", "fun"]
Reverse the array
Array.Reverse changes the array to ["fun", "is", "C#"]
Join the words
string.Join(' ', words) results in "fun is C#"
| Step | Words Array |
|---|---|
| After Split | ["C#", "is", "fun"] |
| After Reverse | ["fun", "is", "C#"] |
| After Join | "fun is C#" |
Why This Works
Step 1: Splitting the string
Using Split(' ') breaks the string into words wherever there is a space.
Step 2: Reversing the words
The Array.Reverse() method reverses the order of the words in the array.
Step 3: Joining the words
Finally, string.Join(' ', words) combines the reversed words back into a single string separated by spaces.
Alternative Approaches
using System; using System.Linq; class Program { static void Main() { string input = "C# is fun"; string reversed = string.Join(' ', input.Split(' ').Reverse()); Console.WriteLine(reversed); } }
using System; class Program { static void Main() { string input = "C# is fun"; string[] words = input.Split(' '); string reversed = ""; for (int i = words.Length - 1; i >= 0; i--) { reversed += words[i] + (i > 0 ? " " : ""); } Console.WriteLine(reversed); } }
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and reversing the array both take linear time proportional to the number of words, so overall time is O(n).
Space Complexity
Extra space is needed to store the array of words, so space complexity is O(n). The reversal is done in-place on the array.
Which Approach is Fastest?
Using Array.Reverse is efficient and simple. LINQ's Reverse() is concise but may have slight overhead. Manual loops are less readable and more error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Array.Reverse | O(n) | O(n) | Simple and efficient reversal |
| LINQ Reverse | O(n) | O(n) | Concise code with LINQ |
| Manual loop | O(n) | O(n) | Understanding reversal logic explicitly |
string.Split and string.Join together with Array.Reverse for a simple and efficient solution.