C# Program - Reverse a given String
In C#, the reverse of a given string can be found out by using below mentioned methods.
Method 1: Using iteration
In the example below, the string called MyString is reversed using ReverseString() method. A variable last is created which points to the last character of the string. An empty string revString is created. By using a for loop and iterating from last to 0, characters from MyString is placed in revMystring in reverse order.
using System; class MyProgram { static void ReverseString(string MyString) { int last = MyString.Length - 1; string revString = string.Empty; for(int i = last; i >= 0; i--) { revString = revString + MyString[i]; } Console.WriteLine(revString); } static void Main(string[] args) { ReverseString("Hello World"); ReverseString("Programming is fun"); ReverseString("Reverse this string"); } }
The above code will give the following output:
dlroW olleH nuf si gnimmargorP gnirts siht esreveR
Method 2: Using Recursion
The above result can also be achieved using recursive method. Consider the example below:
using System; class MyProgram { static void ReverseString(string MyString) { if ((MyString == null) || (MyString.Length <= 1)) { Console.Write(MyString); } else { Console.Write(MyString[MyString.Length-1]); ReverseString(MyString.Substring(0,(MyString.Length-1))); } } static void Main(string[] args) { ReverseString("Hello World"); Console.WriteLine(); ReverseString("Programming is fun"); Console.WriteLine(); ReverseString("Reverse this string"); Console.WriteLine(); } }
The above code will give the following output:
dlroW olleH nuf si gnimmargorP gnirts siht esreveR
Method 3: Printing the string in reverse order
The same can be achieved by printing the string in reverse order. Consider the example below:
using System; class MyProgram { static void ReverseString(string MyString) { int last = MyString.Length - 1; for(int i = last; i >= 0; i--) { Console.Write(MyString[i]); } Console.WriteLine(); } static void Main(string[] args) { ReverseString("Hello World"); ReverseString("Programming is fun"); ReverseString("Reverse this string"); } }
The above code will give the following output:
dlroW olleH nuf si gnimmargorP gnirts siht esreveR
Recommended Pages
- C# - Swap two numbers
- C# Program - Fibonacci Sequence
- C# Program - Insertion Sort
- C# Program - Find Factorial of a Number
- C# Program - Find HCF of Two Numbers
- C# Program - Merge Sort
- C# Program - Shell Sort
- Stack in C#
- Queue in C#
- C# Program - Find LCM of Two Numbers
- C# Program - To Check Whether a Number is Palindrome or Not
- C# Program - To Check Whether a String is Palindrome or Not
- C# Program - Heap Sort
- C# Program - Quick Sort
- C# - Swap Two Numbers without using Temporary Variable
- C# Program - To Check Armstrong Number
- C# Program - Counting Sort
- C# Program - Radix Sort
- C# Program - Find Largest Number among Three Numbers
- C# Program - Print Floyd's Triangle