-
Reverse a String
-
1. Write a program to reverse a string.
Explanation:using System; class Program { static void Main() { string input = "hello"; char[] charArray = input.ToCharArray(); Array.Reverse(charArray); string reversed = new string(charArray); Console.WriteLine("Reversed string: " + reversed); } }- Convert string to a char[].
- Use Array.Reverse().
- Recreate the string.
2. Write a program to reverse a string without extension methods.
Let’s solve it manually using a loop.
Explanation:using System; class Program { static void Main() { string input = "hello"; string reversed = ""; // Traverse string from end to start for (int i = input.Length - 1; i >= 0; i--) { reversed += input[i]; } Console.WriteLine("Reversed string: " + reversed); } }- Start with an empty string - reversed.
- Loop from the last character (input.Length - 1) down to the first.
- Append each character to reversed.
- Finally, print the reversed string