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?
Stack-based solution.
Or
As simple as this:
See the output.
Here a solution that properly reverses the string
"Les Mise\u0301rables"
as"selbare\u0301siM seL"
. This should render just likeselbarésiM seL
, notselbaŕesiM seL
(note the position of the accent), as would the result of most implementations based on code units (Array.Reverse
, etc) or even code points (reversing with special care for surrogate pairs).(And live running example here: https://ideone.com/DqAeMJ)
It simply uses the .NET API for grapheme cluster iteration, which has been there since ever, but a bit "hidden" from view, it seems.
Don't bother with a function, just do it in place. Note: The second line will throw an argument exception in the Immediate window of some VS versions.
This is turning out to be a surprisingly tricky question.
I would recommend using Array.Reverse for most cases as it is coded natively and it is very simple to maintain and understand.
It seems to outperform StringBuilder in all the cases I tested.
There is a second approach that can be faster for certain string lengths which uses Xor.
Note If you want to support the full Unicode UTF16 charset read this. And use the implementation there instead. It can be further optimized by using one of the above algorithms and running through the string to clean it up after the chars are reversed.
Here is a performance comparison between the StringBuilder, Array.Reverse and Xor method.
Here are the results:
It seems that Xor can be faster for short strings.