Header add

In this article we will discuss Reverse a string in C#.

In this article we will not look at the Reverse method provided by the .NET libraries; we will instead try to implement it by our own logic. However we will be using the ToCharArray method in most of our examples.

Reversing a string is a popular question in most campus hiring interviews. There could be several ways one can think of to do this.

1st Way

Using Two Arrays - One to store the input and another for the output and uses two variables to traverse from the beginning and end and assigns the values from the input array to the output array.

public class Program
{
static void Main(string[] args)
{
string str = "";
string reverseString = "";
Console.WriteLine("Enter a Word");
str = Console.ReadLine();
reverseString = stringReverseWithTwoArray(str);
Console.WriteLine(reverseString);
Console.ReadLine();
}
public static string stringReverseWithTwoArray(string str)
{
char[] chars = str.ToCharArray();
char[] result = new char[chars.Length];
for (int i = 0, j = str.Length - 1; i < str.Length; i++, j--)
{
result[i] = chars[j];
}
return new string(result);
}
}

Output




2nd  Way

Using Swap Array - Here we will use the swapping for the same also if you look at, we are only traversing half of the array.


public static string stringReverseWithSwapArray(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);
}

3rd  Way

Using Swap Array - Here we will use any temp variable, so this is for you, here we are using an in-pace swap.

public static string stringReverseWithTemp(string str)
{
char[] chars = str.ToCharArray();
for (int i = 0, j = str.Length - 1; i < j; i++, j--)
{
chars[i] = str[j];
chars[j] = str[i];
}
return new string(chars);
}


4th  Way

Using Swap Array - Here we will use without copy to char array.


///String Reversal without Copy to Char Array it's i <= j as we need to getthe middle /// character in case of odd number of characters in the string
public static string stringReverseWithCopyToChar(string str)
{
char[] chars = new char[str.Length];
for (int i = 0, j = str.Length - 1; i <= j; i++, j--)
{
chars[i] = str[j];
chars[j] = str[i];
}
return new string(chars);
}


Summary
Previous Post Next Post