I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:
public string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
Of course you can extend string class with Reverse method
How about use Substring
Greg Beech posted an
unsafe
option that is indeed as fast as it gets (it's an in-place reversal); but, as he indicated in his answer, it's a completely disastrous idea.That said, I'm surprised there is so much of a consensus that
Array.Reverse
is the fastest method. There's still anunsafe
approach that returns a reversed copy of a string (no in-place reversal shenanigans) significantly faster than theArray.Reverse
method for small strings:Here are some benchmark results.
You can see that the performance gain shrinks and then disappears against the
Array.Reverse
method as the strings get larger. For small- to medium-sized strings, though, it's tough to beat this method.Output
For size: 10
For size: 100
For size: 1000
For size: 10000
Try using Array.Reverse
If you have a string that only contains ASCII characters, you can use this method.