Sometimes we will have requirement to make input string reverse. There are different ways to make string as reverse. In this article we discuss about two ways to make string reverse.
In the first way we will make input string as reverse by using for loop as shown below.
using System;
using System.Windows.Forms;
namespace StringReverseCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string str = "This is String";
string sReverseString = string.Empty;
char[] arr = str.ToCharArray();
//1st Method
for (int i = arr.Length - 1; i >= 0; i--)
{
sReverseString = sReverseString + arr[i];
}
MessageBox.Show(sReverseString);
}
}
}
But by using for loop to make string as reverse is very costly as performance-wise. In the second method we use the Reverse method of Array class as shown below.
using System;
using System.Windows.Forms;
namespace StringReverseCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string str = "This is String";
string sReverseString = string.Empty;
char[] arr = str.ToCharArray();
//2nd Method
Array.Reverse(arr);
sReverseString = new string(arr);
MessageBox.Show(sReverseString);
}
}
}
This is the good approach because here we are reversing the string by converting the input string into arrays.