C# Tips & Tricks: String Reversal
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";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.
The second way we can reverse a string is with the static Array.Reverse() method:
string input = "hello world";First we convert the string to a character array, then we revert the array, and finally we construct a new string from the array.
LINQ allows us to shorten string reversal into a one-liner:
string input = "hello world";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 StringExtensionsWith this class in our code, we can now easily reverse any string:
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.
Andreas Hartl, 2010-2011