C# Examples

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:

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




5