C# Reverse String

You want to reverse the individual characters in a string in your program targeting the .NET Framework. You may use this method in a loop thousands of times, so performance is important, but you also need to review it quickly. Here we see how you can efficiently reverse the characters in a string in the C# programming language.

Input:  [1] framework
        [2] samuel
        [3] example string

Output: [1] krowemarf
        [2] leumae
        [3] gnirts elpmaxe

Reversing strings

First, there are many solutions, but this one can be done with three lines of code. The method shown in this article is based on the author's work with ToCharArray, and the method is static because it does not need to save state. This article is based on .NET 3.5 SP1.

=== Example program that reverses strings (C#) ===

using System;

static class StringHelper
{
    /// <summary>
    /// Receives string and returns the string with its letters reversed.
    /// </summary>
    public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(StringHelper.ReverseString("framework"));
        Console.WriteLine(StringHelper.ReverseString("samuel"));
        Console.WriteLine(StringHelper.ReverseString("example string"));
    }
}

=== Output of the program ===

krowemarf
leumas
gnirts elpmaxe

Overview. The method above receives a string parameter, which is the string in which you wish to reverse the order of the letters. The method is static because it doesn't store state. It calls the static Array method called Reverse to modify the order of the chars.

See Array.Reverse Inverts Array Ordering.

Control flow of method. It copies to an array using the ToCharArray instance method on the string class. This returns the mutable char[] buffer from the string. It returns a string with the new string constructor, which we pass the char[] buffer to. This is our final reversed string.

See ToCharArray Method, Converting String to Array.

Performance

Here we note the performance characteristics of the method. Using ToCharArray on strings for modifications is often quite efficient. Justin Rogers from Microsoft offers some detailed benchmarking.

Visit weblogs.asp.net.

Summary

Here we saw a method that can receive a string and then return the string with its characters in the reverse order. It is one of many examples of using char[] arrays for string manipulation in the C# language. The code isn't useful often, but it may help for an interview question or two. This article is found in the Sorting category on Dot Net Perls.

See Sort Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen