Ian Beckett

RSS feed

    Recent comments

    Authors

    StringHelper class to reverse strings using C#

    I was surprised to find that C# does not have a built in method to reverse strings.  A quick search on Bing brought up the below code snippet from Sam Allen at dotnetperls.com.  The StringHelper class below contains a single static method named ReverseString.  Works like a charm!

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

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

    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"));
        }
    }


    Posted by ibeckett on Tuesday, August 11, 2009 12:04 AM
    Permalink | Comments (0) | Post RSSRSS comment feed