Click here to monitor SSC

Reverse a string

Last post 08-05-2006, 12:06 PM by Adam Machanic. 10 replies.
Sort Posts: Previous Next
  •  06-28-2006, 2:21 AM Post number 931

    Reverse a string

    I know it seems a very simple question but I can't seem to find out a way to reverse a string in .NET 1.1 or 2.0.

    I can't believe that microsoft ommitted something that basic from the system.
  •  06-28-2006, 9:59 AM Post number 950 in reply to post number 931

    Re: Reverse a string

    I'm not sure why MS does not put a standard string reverse mechanism into the BCL (I agree, it's odd to leave this out considering that virtually every other language/framework has it)... however, there is a clever way of doing it:

    yourString = yourString.split("").reverse().join("");


    This converts the string into an array of characters, then reverses the array and converts the array back into a string.  If you're really concerned about efficiency, this is not the best way of achieving this goal -- instead you should write your own code to loop over the string and perhaps use the StringBuilder class.  But this method  is definitely the simplest from a coding perspective.


  •  06-28-2006, 10:01 AM Post number 951 in reply to post number 931

    • Damon is not online. Last active: 02-28-2014, 9:16 AM Damon
    • Top 10 Contributor
    • Joined on 06-26-2006
    • Dallas, TX
    • Atari ST

    Re: Reverse a string

    Wow, they don't.  That's pretty odd.  Here's one way to do it without having to write your own loop:

    string myString = "Hello world";
    char[] rev = myString.ToCharArray();
    Array.Reverse(rev);
    string myReverseString = new string(rev);

  •  06-30-2006, 9:24 AM Post number 1021 in reply to post number 951

    Re: Reverse a string

    I know that was my reaction. Mind you I do like the ability to string.Replace("Fred","YellowIsNotMyFavouriteColour"). But then I come from a C background, strtok() anyone :).

    Still I think it's an omission.

  •  07-17-2006, 11:59 AM Post number 1292 in reply to post number 951

    Re: Reverse a string

    Damon:

    string myString = "Hello world";
    char[] rev = myString.ToCharArray();
    Array.Reverse(rev);
    string myReverseString = new string(rev);

    To my eyes, that's an overly complicated way to reverse a string. Try this:

    public static string Reverse ( string s )
    {
      StringBuilder sb = new System.Text.StringBuilder( s.Length ) ;
      int           i  = s.Length ;
    
      while ( i-- > 0 )
      {
        sb.Append( s[i] ) ;
      }
    
      return sb.ToString() ;
    
    }
    
  •  07-17-2006, 2:00 PM Post number 1303 in reply to post number 1292

    Re: Reverse a string

    Some more thoughts on this here:

    http://sqlblog.com/blogs/adam_machanic/archive/2006/07/17/116.aspx

    (Following is the text of the blog so that we can continue to discuss here -- I don't want to hijack this thread, just thought that it made for good blog fodder!)


    ---
    Over in the Simple-Talk forums, there is a good thread going about how best to reverse a string in .NET, since no string reverse method is included in the BCL.

    A few suggestions were made, and someone implied that they were too complex and that simplicity is the most important factor.  Personally, I wonder -- does complexity really matter in this case?  I would expect that you'd program this kind of thing exactly once, put it into a utility class somewhere, and never worry about the implementation again.  Given that assumption, it becomes more of a performance question for me.

    To that end, I've run a few tests.  I created three methods -- the first is a method using StringBuilder, as suggested by one of the respondants in the thread who felt it was the simplest method of achieving tho goal.  The second uses Array.Reverse, and is perhaps slightly more obscure.  The third method is a modification of the first, in which the main loop iterates over an array of chars instead of the string, which I had a hunch would be faster (alas, tests show that I was not correct in my assumption).  Following are the methods:

            public static string Reverse1(string s)
            {
                StringBuilder sb = new System.Text.StringBuilder(s.Length);
                int i = s.Length;

                while (i-- > 0)
                {
                    sb.Append(s[i]);
                }

                return sb.ToString();
            }

            public static string Reverse2(string s)
            {
                char[] rev = s.ToCharArray();
                Array.Reverse(rev);
                return (new string(rev));
            }

            public static string Reverse3(string s)
            {
                char[] charArray = s.ToCharArray();

                int i = charArray.Length;

                StringBuilder sb = new System.Text.StringBuilder(i);           

                while (i-- > 0)
                {
                    sb.Append(s[i]);
                }

                return sb.ToString();
            }


    I turned on Visual Studio's profiler to collect timings and ran these methods in a loop.  First test was reversing 26 characters (a-z), which I ran in a loop 10,000 times for each method.  Results:

    Reverse1: 506.775 ms
    Reverse2: 58.327 ms
    Reverse3: 522.484 ms

    The second test was reversing 2080 characters (a-z repeated 80 times).  I was only able to run this test in the loop 2500 times, as my workstation is currently very low on disk space and the VS profiler's output takes up a lot of room.  Results:

    Reverse1: 2060.424 ms
    Reverse2: 117.874 ms
    Reverse3: 2368.861 ms

    Results are total time spent in each function and its children over the course of all iterations.

    So for me, the Array.Reverse method is what I would use... Anyone out there have a better version to share?
    ---

  •  07-18-2006, 12:11 AM Post number 1312 in reply to post number 931

    Re: Reverse a string

    Run this through the profiler.  I didn't test it, but it seems to be functional and optimized.

        public void ReverseString( StringBuilder aString )
        {
            int left = 0;
            int right = aString.Length - 1;

            while ( left < right )
            {
                char t = aString[ left ];
                aString[ left ] = aString[ right ];
                aString[ right ] = t;

                left++;
                right--;
            }
        }
  •  07-18-2006, 12:41 AM Post number 1313 in reply to post number 1312

    Re: Reverse a string

    I changed the interface to string in and string out to comply with the rest of the tests:

            public static string Reverse6(string s)
            {
                StringBuilder aString = new StringBuilder(s);

                int left = 0;
                int right = aString.Length - 1;

                while (left < right)
                {
                    char t = aString[left];
                    aString[left] = aString[right];
                    aString[right] = t;

                    left++;
                    right--;
                }

                return (aString.ToString());
            }

    Unfortunately, it appears to be the 2nd slowest method I've tested to date (see my blog for the updated versions of the other 5 if you're interested in testing on your end.)

  •  07-18-2006, 9:57 PM Post number 1329 in reply to post number 1313

    • Damon is not online. Last active: 02-28-2014, 9:16 AM Damon
    • Top 10 Contributor
    • Joined on 06-26-2006
    • Dallas, TX
    • Atari ST

    Re: Reverse a string

    Hey Adam, thanks for going to the trouble of actually performance testing all of these options!
  •  08-04-2006, 5:54 PM Post number 1528 in reply to post number 931

    • copilot is not online. Last active: 2006-10-16, 7:17 PM copilot
    • Not Ranked
    • Joined on 08-04-2006
    • Tucson, AZ
    • Level 1: Deep thought

    Re: Reverse a string

    I was also looking for a String.Reverse the other day and I happened to stumble upon this guy's "contest".  Looks like you guys were all on the same page. 

    http://weblogs.asp.net/justin_rogers/archive/2004/06/10/153175.aspx

    and then someone showed an unsafe pointer arithmetic method

    http://weblogs.asp.net/justin_rogers/archive/2004/06/12/154375.aspx

  •  08-05-2006, 12:06 PM Post number 1539 in reply to post number 1528

    Re: Reverse a string

    copilot:
    I was also looking for a String.Reverse the other day and I happened to stumble upon this guy's "contest".



    And here's even more...

    http://codebetter.com/blogs/gregyoung/archive/2006/07/21/147569.aspx

    I don't think the debate will end until MS includes this in the BCL!




View as RSS news feed in XML