In this article, we will be creating program to reverse a string in C# using various possible methods, so first create a new console application in your Visual Studio.
To Create console application in Visual Studio, navigate to File-> New -> Project -> Select "Windows Desktop" from left pane and "Console Application" from right-pane.
Reverse string using third variable (for loop)
using System;
namespace ReverseString
{
class Program
{
static void Main(string[] args)
{
var str = "New string";
var r = reverseStringusingThirdVariable(str);
Console.WriteLine(r);
}
public static string reverseStringusingThirdVariable(string str)
{
char[] chars = str.ToCharArray();
for (int i = 0, j = str.Length - 1; i < j; i++, j--)
{
char c = chars[i];
chars[i] = chars[j];
chars[j] = c;
}
return new string(chars);
}
}
}
Output:
gnirts weN
In the above method, we are passing string to a method, which initially converts string into char array, then loop through each value of char arraye and using third variable, places the first char in last position and so on.
Reverse string using Foreach loop
using System;
namespace ReverseString
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string to reverse :");
string name = Console.ReadLine();
string reverseString = string.Empty;
foreach (char c in name)
{
reverseString = c + reverseString;
}
Console.WriteLine(reverseString);
}
}
}
Output
Enter the string to reverse :
New main
niam weN
In the above method, we are creating new string, by looping original string as char using foreach loop, then saving last character as first in new string.
Reverse string using Array (Easy and quick method)
using System;
namespace ReverseString
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string to reverse :");
string name = Console.ReadLine();
char[] charArray = name.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
}
}
}
Output
Enter the string to reverse :
Plain text
txet nialP
You may also like to read: