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?
If you want to play a really dangerous game, then this is by far the fastest way there is (around four times faster than the
Array.Reverse
method). It's an in-place reverse using pointers.Note that I really do not recommend this for any use, ever (have a look here for some reasons why you should not use this method), but it's just interesting to see that it can be done, and that strings aren't really immutable once you turn on unsafe code.
I've made a C# port from Microsoft.VisualBasic.Strings. I'm not sure why they keep such useful functions (from VB) outside the System.String in Framework, but still under Microsoft.VisualBasic. Same scenario for financial functions (e.g.
Microsoft.VisualBasic.Financial.Pmt()
).Faster than above method
Firstly you don't need to call
ToCharArray
as a string can already be indexed as a char array, so this will save you an allocation.The next optimisation is to use a
StringBuilder
to prevent unnecessary allocations (as strings are immutable, concatenating them makes a copy of the string each time). To further optimise this we pre-set the length of theStringBuilder
so it won't need to expand its buffer.Edit: Performance Data
I tested this function and the function using
Array.Reverse
with the following simple program, whereReverse1
is one function andReverse2
is the other:It turns out that for short strings the
Array.Reverse
method is around twice as quick as the one above, and for longer strings the difference is even more pronounced. So given that theArray.Reverse
method is both simpler and faster I'd recommend you use that rather than this one. I leave this one up here just to show that it isn't the way you should do it (much to my surprise!)The easy and nice answer is using the Extension Method:
and here's the output: