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.
| Input | Output |
| "framework" | "krowemarf" |
| "samuel" | "leumae" |
| "example string" | "gnirts elpmaxe" |
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);
}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.
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.
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.