Dot Net Perls

Reverse String - C#

by Sam Allen

Problem

Efficiently reverse the individual characters in a string. Often when you do this, you will need to do it many thousands of times, so performance is important. However, we also require an elegant and easy-to-maintain solution.

InputOutput
"framework""krowemarf"
"samuel""leumae"
"example string""gnirts elpmaxe"

Solution: C#

Many developers far more skilled than I am have mused on this problem. There are many solutions, but in my opinion there is a clear winner. This particular one was based on my work with ToCharArray. This code is static because it does not need to save state.

/// <summary>
/// Reverse a string so that the letters are in the opposite order.
/// </summary>
/// <param name="toReverse">The string you want to reverse.</param>
/// <returns>The reversed output string.</returns>
public static string ReverseString(string toReverse)
{
    //
    // Convert the parameter string to a char array, then call Array's static
    // Reverse method, then return a new string based on the char[].
    //
    char[] charArray = toReverse.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}
  1. It receives a string.
    The above method receives a string parameter, which is the string you wish to reverse the order of the letters in.
  2. It copies to array.
    We copy the string contents to a character array using the ToCharArray instance method on the string class.
  3. Method is static.
    Our method calls the static Array function called Reverse to modify the order of the chars. This is not the fastest way to do this, but it is definitely the simplest.
  4. It returns string.
    The new string constructor in the final code line allocates a new string from the character array. You must pass it the char[] array. Finally, the result is returned.

Why is it faster?

Because it uses ToCharArray. Using ToCharArray on strings for modifications is often quite efficient. Justin Rogers on his post called Fastest String Reversing offers some detailed benchmarking.

Why is native code faster?

The .NET platform is written in native code, but your .NET programs run in managed C# code. This means that pushing as much processing to the native runtime code is going to result in a performance boost.

Conclusion

My recommendation is to use the Array Reverse. Often an extreme outlier situation can really define the performance of a program. So, by being much faster on very long strings, this approach might be overall the fastest.

Reverse words. Sometimes you need to reverse the individual words in a string. I have an analysis and clear example of this operation as well. Read about it in Reverse Words.

Dot Net Perls
About
Sitemap
Strings
IndexOf String Examples
Remove Duplicate Words From...
Remove HTML Tags From String
Replace String Examples
Split String Examples
New
Occurrence Count of String
StartsWith String Examples
© 2008 Sam Allen. All rights reserved.