In this article I will explain about how to reverse string in C# with simple example. We can reverse the string in C# by using CharArray. First convert the string into character array, then reverse the array by using Reverse() method of array.
Let’s discuss with simple example.
Create Console Application by opening Visual studio => Create Project => Select Console Application.
Add Class by selecting Add option from Solution Explorer => New Item =>Select class and name it as StringUtilities.cs.
Add ReverseString() method to StringUtilities class as shown below.
class StringUtilities
{
public static string StringReverse(string str)
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
As shown above, first convert the string into char array and reverse the array by using Reverse() method of Array class. Call this StringReverse() method from client as shown below.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter string to reverse");
string stringInput = Console.ReadLine();
Console.WriteLine(StringUtilities.StringReverse(stringInput));
Console.ReadLine();
}
}
Run the application and enter input as “ABC DEF” and you will get the output as shown below.