In this blog post, we will see how we can reverse a string in C#.
Reversing a string can be used in a few different scenarios. One of the use case can be an interview question.
Reverse A String In C# Using Array.Reverse()
Method
This will be the fastest and the best way to reverse a string in C#.
In this method, we convert a string that needs to be reversed into a char array.
Using this char array, we use the Array.Reverse()
method and supply the char array to this method as a parameter.
We then get a char array which is now in reverse.
The final step is to join this char array back to a string. We do that using a new string()
method and pass the char array to it.
Let's have a look at the code example:
Example:
namespace ConsoleApp3 { public class Program { public static void Main() { string sample = "This is a string"; char[] charArray = sample.ToCharArray(); Array.Reverse(charArray); string reverseString = new string(charArray); Console.WriteLine(reverseString); } } }
Result:
gnirts a si sihT
Reverse A String In C# Using For
Loop
Although the above method is the fastest and the best method to reverse a string in C#, there can be a few other methods as well.
One of them can be to use a for
loop instead.
Let's see this in a code example.
Example:
namespace ConsoleApp3 { public class Program { public static void Main() { string sample = "This is a string"; char[] charArray = sample.ToCharArray(); for (int i = 0, j = charArray.Length - 1; i < j; i++, j--) { charArray[i] = sample[j]; charArray[j] = sample[i]; } string reverseString = new string(charArray); Console.WriteLine(reverseString); } } }
Result:
gnirts a si sihT