C# Program to Reverse a String

In this article, I will be writing a C# Program to Reverse a String. I will be explaining the whole program stepwise. It is a common interview question for freshers.

Program Overview

We are going to solve a commonly asked question in C# Programming. We are going to write a C# Program to Reverse a String. I will be using the switch-case method in C# Program to Reverse a String.

Algorithm to Reverse a String

Step 1. Start
Step 2. Read the string from the user
Step 3. Calculate the length of the string
Step 4. Initialize rev = “ ” [empty string]
Step 5. Initialize i = length – 1
Step 6. Repeat until i>=0: 6.1: rev = rev + Character at position ‘i’ of the string 6.2: i = i – 1
Step 7. Print rev
Step 8. Stop

Flowchart to C# Program to Reverse a String

C# Program to Reverse a String

Here’s the C# Program to Reverse a String:

using System;
class Demo {
   static void Main() {
      string myStr, rev;
      myStr = "Tom";
      rev ="";
      Console.WriteLine("Your String is {0}", myStr);
      int len;
      len = myStr.Length - 1;
      while (len >= 0) {
         rev = rev + myStr[len];
         len--;
      }
      Console.WriteLine("The Reversed String is {0}", rev);
      Console.ReadLine();
   }
}

Output

Here’s the output of the C# Program to Reverse a String:

C# Program to Reverse a String
groot
groot

Leave a Reply

Your email address will not be published. Required fields are marked *