C# program to reverse a string



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
Updated on: 2020-06-19T11:32:09+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements