How to Reverse a String in C#?

Introduction

We are going to discuss various ways available to reverse the string in the c# programming language. This is one of the important Technical interview questions which has asked for beginner, intermediate and experience candidates.

  1. Using Built-in string function.
  2. Using Built-in Array function
  3. Using For Loop
  4. Using ForEach Loop

Let’s start with Build-in string function,

Built-in String function

We will utilize the string.Reverse() built in function to reverse the string.  

First Create Console application and write the below code in the program.cs file, 

var str = Console.ReadLine();
String strReverse = new string(str.Reverse().ToArray());
Console.WriteLine(strReverse);
Console.ReadLine();

Output

Built-in String function

Build-in Array Function

We will use Array.Reverse() built in function for this.

var str = Console.ReadLine();
Char[] stringArr = str.ToCharArray(); 
Array.Reverse(stringArr);
string strReverse = new string(stringArr);
Console.WriteLine(strReverse);
Console.ReadLine();

Output

Build-in Array Function

Using ForLoop

Let’s try with ForLoop.

var str = Console.ReadLine();
Char[] stringArr = str.ToCharArray(); 
string strReverse = string.Empty;

for (int i = (stringArr.Length-1); i>=0; i--)
{
    strReverse += stringArr[i];
}
Console.WriteLine(strReverse);
Console.ReadLine();

Output

Using ForLoop

Using ForEach Loop

We can do it using ForEach Loop.

var str = Console.ReadLine();
Char[] stringArr = str.ToCharArray(); 
string strReverse = string.Empty;

foreach (char c in stringArr)
{
    strReverse = c + strReverse;
}

Console.WriteLine(strReverse);
Console.ReadLine();

Output

Using ForEach Loop

That’s all for this article. We will cover more interview questions. Hope you enjoyed article.


Similar Articles