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?
How about:
If it ever came up in an interview and you were told you can't use Array.Reverse, i think this might be one of the fastest. It does not create new strings and iterates only over half of the array (i.e O(n/2) iterations)
If the string contains Unicode data (strictly speaking, non-BMP characters) the other methods that have been posted will corrupt it, because you cannot swap the order of high and low surrogate code units when reversing the string. (More information about this can be found on my blog.)
The following code sample will correctly reverse a string that contains non-BMP characters, e.g., "\U00010380\U00010381" (Ugaritic Letter Alpa, Ugaritic Letter Beta).
Sorry for posting on this old thread. I am practicing some code for an interview.
This was what I came up with for C#. My first version before refactoring was horrible.
In Contrast to the
Array.Reverse
method below, it appears faster with 12 characters or less in the string. After 13 characters, theArray.Reverse
starts to get faster, and it eventually dominates pretty heavily on speed. I just wanted to point out approximately where the speed starts to change.At 100 characters in the string, it is faster than my version x 4. However, if I knew that the strings would always be less than 13 characters, I would use the one I made.
Testing was done with
Stopwatch
and 5000000 iterations. Also, I'm not sure if my version handles Surrogates or combined character situations withUnicode
encoding."Better way" depends on what is more important to you in your situation, performance, elegance, maintainability etc.
Anyway, here's an approach using Array.Reverse: