C# program to reverse a string

This post was published to show you the information and program in C# that show how we can reverse a string. I have created two programs, one with user input and the other without user input.

Simple C# program to reverse a string

Let me first create a C# program that reverses a string and prints the reverse of the string on the output console. This program does not allow the user to enter any input.

string origString = "fresherearth";
string revString = "";
int len;

len = origString.Length - 1;

while (len >= 0)
{
    revString = revString + origString[len];
    len--;
}

Console.WriteLine("Reverse = " + revString);

The output produced by this C# program should exactly be:

Reverse = rekcarcsedoc

The same C# program can also be written as

string origString = "fresherearth", revString = "";

for (int len = origString.Length - 1; len >= 0; len--)
    revString = revString + origString[len];

Console.WriteLine("Reverse = " + revString);

C# program to reverse a string entered by user

Now let me create another C# program that does the same thing, except that this program receives a string from the user at run-time of the program.

string origString, revString = ""; 

Console.WriteLine("Enter the string: ");
origString = Console.ReadLine();

for (int len = origString.Length - 1; len >= 0; len--)
    revString = revString + origString[len];

Console.WriteLine("\nReverse = " + revString);

The sample run with user input "C# programming is fun!" is shown in the snapshot given below.

c sharp reverse string

C# Online Test


« Previous Program Next Program »