How to reverse a string in C#
Reverse a string using iterative method
The algorithm to reverse a string in C# is as follows:
Convert the string into an array of characters using the
ToCharArray()method.Reverse the character array using
Array.Reversemethod.Create a new string from the reversed array. This will result in reversing the original string.
Example
Let's write the C# program to reverse the string.
using System;class ReverseString{static void Main(string[] args){string str = "Educative";char[] stringArray = str.ToCharArray();Array.Reverse(stringArray);string reversedStr = new string(stringArray);Console.Write($"Actual String is : {str} \n");Console.Write($"Reversed String is : {reversedStr} ");}}
Explanation
Here's the explanation for the code above.
Line 6: We'll create a string variable with the name
strand assign it a valueEducative.Line 7: We'll use the
ToCharArray()method to convert the string to a character array and store it in the variablestringArray.Line 8: We'll use the
Array.reverse()method to reverse thestringArray.Line 9: We'll create a new string variable
reversedStrfrom thestringArray. ThereversedStrcontains the original string in reverse.
Reverse a method using a StringBuilder
StringBuilder is a mutable string in C#. It helps to modify strings. It provide methods to modify, append, insert, and remove characters from a string without creating a new instance every time.
using System;using System.Text;class ReverseString{static void Main(string[] args){string str = "Educative";string reversedStr = Reverse(str);Console.WriteLine(reversedStr);}static string Reverse(string str){StringBuilder reversed = new StringBuilder();for (int i = str.Length - 1; i >= 0; i--){reversed.Append(str[i]);}return reversed.ToString();}}
Explanation
Line 6: We'll create a string variable with the name
strand assign it a valueEducative.Line 9: We declare a variable
reversedStr, this will hold the output fromReversemethod with the stringstras an argument. This method reverses the string.Line 15: We initialize the instance of
StringBuilder.
Free Resources