Here we will see 2 variants of for loop to reverse a given input string.
In order to execute the code I’ve created a simple console application to print out the result.
Please find complete code below:
- Option 1
using System; namespace PracticeConsole { class Program { static void Main(string[] args) { Console.WriteLine("Please enter a string of your choice and then hit enter:"); string myString = Console.ReadLine(); string reversedString = ""; for (int i = myString.Length - 1; i >= 0; i--) { reversedString += myString[i].ToString(); } Console.WriteLine(reversedString); Console.ReadLine(); } } }
Result:
2. Option 2
using System; namespace PracticeConsole { class Program { static void Main(string[] args) { Console.WriteLine("Please enter a string of your choice and then hit enter:"); string myString = Console.ReadLine(); char[] charArray = myString.ToCharArray(); for (int i = 0, j = myString.Length - 1; i < j; i++, j--) { charArray[i] = myString[j]; charArray[j] = myString[i]; } string reversedString = new string(charArray); Console.WriteLine(reversedString); Console.ReadLine(); } } }
Result: