C# program to reverse a string

CsharpServer Side ProgrammingProgramming

Our sample string is −

myStr = "Tom";

To reverse the string, firstly find the length of the string −

// find string length
int len;
len = myStr.Length - 1;

Now, use a while loop until the length is greater than 0 −

while (len >= 0) {
   rev = rev + myStr[len];
   len--;
}

Example

You can try to run the following code to reverse a string in C#.

Live Demo

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

Output

String is Tom
Reversed String is moT
raja
Published on 25-Jul-2018 11:25:59
Advertisements