In C#, if you are given a string and asked to reverse that string, below code will be helpful for you.
INPUT => VIJAY PANDEY
OUTPUT => YEDNAP YAJIV
Step 1. Create a console application
Step 2. Follow below code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the string to be reversed :");
string stringTobeReversed = Console.ReadLine();
Console.WriteLine(GetReverseString(stringTobeReversed));
Console.ReadKey();
INPUT => VIJAY PANDEY
OUTPUT => YEDNAP YAJIV
Step 1. Create a console application
Step 2. Follow below code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the string to be reversed :");
string stringTobeReversed = Console.ReadLine();
Console.WriteLine(GetReverseString(stringTobeReversed));
Console.ReadKey();
}
#region Method to reverse a given string
private static string GetReverseString(string str)
{
string revstr = string.Empty; // take an empty string to hold the reversed string
#region using FOR LOOP
// Start for loop from string length -1 and proceed till the index not equals to -1.
// Continue decreasing the index
for (int i = str.Length - 1; i != -1; i--)
{
revstr += str[i]; // append each character of the string to the empty string we already have
}
return revstr;
#endregion
#region Using WHILE LOOP
// Similarly, we can do this using While loop
int length = str.Length - 1;
revstr = string.Empty;
while (length >= 0)
{
revstr += str[length];
length--;
}
return revstr;
#endregion
}
#endregion
private static string GetReverseString(string str)
{
string revstr = string.Empty; // take an empty string to hold the reversed string
#region using FOR LOOP
// Start for loop from string length -1 and proceed till the index not equals to -1.
// Continue decreasing the index
for (int i = str.Length - 1; i != -1; i--)
{
revstr += str[i]; // append each character of the string to the empty string we already have
}
return revstr;
#endregion
#region Using WHILE LOOP
// Similarly, we can do this using While loop
int length = str.Length - 1;
revstr = string.Empty;
while (length >= 0)
{
revstr += str[length];
length--;
}
return revstr;
#endregion
}
#endregion
}
No comments:
Post a Comment