C# - How to Reverse a String

Unfortunately, C#'s string class is missing a Reverse() function, so here are three ways to reverse strings:

1. Manual Reversal

The most obvious way is to reverse a string by manually walking through it character for character and building a new string:

string input = "hello world";
string output = "";
for (int i = input.Length - 1; i >= 0; i--)
{
    output += input[i];
}
Note that if you take this approach in a serious program, you should use StringBuilder instead of string, since in the above code, a new temporary string is created each time you add a single character to the output string.

2. Array.Reverse()

The second way we can reverse a string is with the static Array.Reverse() method:
string input = "hello world";
char[] inputarray = input.ToCharArray();
Array.Reverse(inputarray);
string output = new string(inputarray);
First we convert the string to a character array, then we revert the array, and finally we construct a new string from the array.

3. LINQ

LINQ allows us to shorten string reversal into a one-liner:
string input = "hello world";
string output = new string(input.ToCharArray().Reverse().ToArray());
First the string is again converted to a char array. Array implements IEnumerable, so we can call LINQ's Reverse() method on it. With a call to ToArray() the resulting IEnumerable is then again converted to a char array, which is used in the string constructor.

For maximum convenience, we can create an extension method on string to do the reversal:
static class StringExtensions
{
    public static string Reverse(this string input)
    {
        return new string(input.ToCharArray().Reverse().ToArray());
    }
}
With this class in our code, we can now easily reverse any string:
Console.WriteLine("hello world".Reverse());

Please be aware however, that all of the above methods for string reversal only work with 16 bit Unicode characters, which fit into one char variable. If you need to reverse strings that include extended Unicode chars, for example chinese kanji, look here.

No comments:

Post a Comment