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.Reverse
method.
Create a new string from the reversed array. This will result in reversing the original string.
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} ");}}
Here's the explanation for the code above.
Line 6: We'll create a string variable with the name str
and assign it a value Educative
.
Line 7: We'll use the ToCharArray()
method to convert the string to a character array and store it in the variable stringArray
.
Line 8: We'll use the Array.reverse()
method to reverse the stringArray
.
Line 9: We'll create a new string variable reversedStr
from the stringArray
. The reversedStr
contains the original string in reverse.
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();}}
Line 6: We'll create a string variable with the name str
and assign it a value Educative
.
Line 9: We declare a variable reversedStr
, this will hold the output from Reverse
method with the string str
as an argument. This method reverses the string.
Line 15: We initialize the instance of StringBuilder
.
Free Resources