- C# Tutorial
- C# Tutorial
- C# Basic Syntax
- C# Operators
- C# if else
- C# switch
- C# Loops
- C# break Vs. continue
- C# Arrays
- C# Strings
- C# Methods
- C# Examples
- C# Add Two Numbers
- C# Swap Two Numbers
- C# Reverse a Number
- C# Reverse a String
- C# Celsius to Fahrenheit
- Computer Programming
- Learn Python
- Python Keywords
- Python Built-in Functions
- Python Examples
- Learn C++
- C++ Examples
- Learn C
- C Examples
- Learn Java
- Java Examples
- Learn Objective-C
- Web Development
- Learn HTML
- Learn CSS
- Learn JavaScript
- JavaScript Examples
- Learn SQL
- Learn PHP
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 = "codescracker";
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 = "codescracker", 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.
« Previous Program Next Program »