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.
- Using Built-in string function.
- Using Built-in Array function
- Using For Loop
- 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
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
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 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
That’s all for this article. We will cover more interview questions. Hope you enjoyed article.