Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. returning a string in reverse

returning a string in reverse

Scheduled Pinned Locked Moved C#
data-structuresquestion
34 Posts 12 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P PIEBALDconsult

    Another http://www.codeproject.com/script/comments/forums.asp?forumid=1649&ForumID=1649&XtraIDs=1649&searchkw=reverse&sd=24%20Aug%202006&ed=22%20Nov%202007&stype=3&Page=4&select=1810365&df=100&exp=1&mpp=50&fr=13817[^] and another http://www.codeproject.com/script/comments/forums.asp?forumid=1649&ForumID=1649&XtraIDs=1649&searchkw=reverse&sd=24%20Aug%202006&ed=22%20Nov%202007&stype=3&Page=4&select=1793424&df=100&exp=1&mpp=50&fr=14253&tid=1793237[^]

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #19

    Yep, just like a similar reverse problem[^] it can be solved with a single line of code, much shorter than each of the posts/replies in this thread... :)

    Luc Pattyn [Forum Guidelines] [My Articles]


    this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


    P 1 Reply Last reply
    0
    • S Skippums

      I prefer the following...

      public void Main()
      {
      string str = "I will do my homework on my own";
      IntPtr strPtr = Marshal.StringToHGlobalUni(str);
      IntPtr resPtr = ReverseString(strPtr);
      string res = Marshal.PtrToStringUni(result);
      Marshal.FreeHGlobal(strPtr);
      Marshal.FreeHGlobal(resPtr);
      Console.WriteLine(str);
      Console.WriteLine(res);
      }

      public IntPtr ReverseString(IntPtr strPtr)
      {
      string str = Marshal.PtrToStringUni(strPtr);
      char[] strAsCharArray = new char[str.Length];
      for (int i = 0; i < str.Length; ++i)
      {
      strAsCharArray[i] = str[0];
      str = str.Substring(1);
      }
      StringBuilder sb = new StringBuilder(strAsCharArray.Length);
      string res = string.Empty;
      for (int i = 0; i < str.Length; i += 2)
      {
      string next = string.Empty;
      for (int j = 1; j >= 0; --j)
      {
      if (i + j == str.Length)
      continue;
      char c = strAsCharArray[i + j];
      next.Insert(0, c.ToString());
      res.Insert(1 - j, c.ToString());
      }
      sb.Append(next);
      }
      str = sb.ToString();
      IntPtr rval = Marshal.StringToHGlobalUni(res);
      return rval;
      }

      This is O(n), which is as fast as this operation can be done given how strings are implemented in the system (with a double-linked-list, it can be O(1)). Hope this helps. Jeff

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #20

      Since you already optimized the code, more in particular by unrolling the for loop, it is actually more like O(n/2) which is quite good. :)

      Luc Pattyn [Forum Guidelines] [My Articles]


      this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


      I S 2 Replies Last reply
      0
      • L Luc Pattyn

        Since you already optimized the code, more in particular by unrolling the for loop, it is actually more like O(n/2) which is quite good. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


        I Offline
        I Offline
        Imran Adam
        wrote on last edited by
        #21

        Thanks all sorted, this is what i used....... public string Reverse(string WhatToReverse) { string str2 = string.Empty; StringBuilder sb = new StringBuilder(); //char array char[] myArray = WhatToReverse.ToCharArray(); for(int i = WhatToReverse.Length-1; i >=0; i--) { sb.Append(myArray[i].ToString()); } str2 = sb.ToString(); return str2; }

        Cheers :)

        S 1 Reply Last reply
        0
        • I Imran Adam

          Thanks all sorted, this is what i used....... public string Reverse(string WhatToReverse) { string str2 = string.Empty; StringBuilder sb = new StringBuilder(); //char array char[] myArray = WhatToReverse.ToCharArray(); for(int i = WhatToReverse.Length-1; i >=0; i--) { sb.Append(myArray[i].ToString()); } str2 = sb.ToString(); return str2; }

          Cheers :)

          S Offline
          S Offline
          Skippums
          wrote on last edited by
          #22

          Good work! Post something like this and ask how to make it better, and we will honestly try to help (instead of the crappy roundabout ways we proposed to solve the problem earlier). The way I would implement this problem is as follows...

          public string ReverseString(string str) {
          StringBuilder result = new StringBuilder();
          for (int i = str.Length - 1; i >= 0; --i)
          result.Append(str[i]);
          return result.ToString();
          }

          Like I said, show that you have put even a little effort into trying to find the answer by yourself, and we will try to give you the help you need to get it right, but don't expect us to give you the answer from scratch. Jeff

          G 1 Reply Last reply
          0
          • L Luc Pattyn

            Of course this is homework, no company is going to pay for string reversals. Maybe class gnirts could help, but sadly it has been postponed till the next major upgrade of the .NET Framework. :doh:

            Luc Pattyn [Forum Guidelines] [My Articles]


            this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


            S Offline
            S Offline
            Skippums
            wrote on last edited by
            #23

            well played. Jeff

            1 Reply Last reply
            0
            • L Luc Pattyn

              Since you already optimized the code, more in particular by unrolling the for loop, it is actually more like O(n/2) which is quite good. :)

              Luc Pattyn [Forum Guidelines] [My Articles]


              this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


              S Offline
              S Offline
              Skippums
              wrote on last edited by
              #24

              Wow... I can't beleive I missed that! :laugh: Jeff

              1 Reply Last reply
              0
              • I Imran Adam

                Hi Guys i would like to know how you can create a simple method to return a string in reverse order. i have the following method public string myMethod (String myString) { . . //code goes in here . return myString } i have been trying to use a array to read the string into and try that but this doesnt seem to work any ideas please??

                Cheers :)

                A Offline
                A Offline
                Andrei Ungureanu
                wrote on last edited by
                #25

                Have you considered using Array.Reverse method?

                string original = "original";
                char[] reverseString = original.ToCharArray();
                Array.Reverse(reverseString);
                original = string.Empty;
                for (int i = 0; i < reverseString.Length; i++)
                original += reverseString[i];

                I will use Google before asking dumb questions

                L 1 Reply Last reply
                0
                • A Andrei Ungureanu

                  Have you considered using Array.Reverse method?

                  string original = "original";
                  char[] reverseString = original.ToCharArray();
                  Array.Reverse(reverseString);
                  original = string.Empty;
                  for (int i = 0; i < reverseString.Length; i++)
                  original += reverseString[i];

                  I will use Google before asking dumb questions

                  L Offline
                  L Offline
                  Luc Pattyn
                  wrote on last edited by
                  #26

                  summing up to new string(Array.Reverse(original.ToCharArray()) or even better a sequence of original.ToCharArray(), Array.Reverse() and new string(char[]) :) -- modified at 15:58 Thursday 22nd November, 2007

                  Luc Pattyn [Forum Guidelines] [My Articles]


                  this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


                  G 1 Reply Last reply
                  0
                  • S Skippums

                    Good work! Post something like this and ask how to make it better, and we will honestly try to help (instead of the crappy roundabout ways we proposed to solve the problem earlier). The way I would implement this problem is as follows...

                    public string ReverseString(string str) {
                    StringBuilder result = new StringBuilder();
                    for (int i = str.Length - 1; i >= 0; --i)
                    result.Append(str[i]);
                    return result.ToString();
                    }

                    Like I said, show that you have put even a little effort into trying to find the answer by yourself, and we will try to give you the help you need to get it right, but don't expect us to give you the answer from scratch. Jeff

                    G Offline
                    G Offline
                    Guffa
                    wrote on last edited by
                    #27

                    Just one adjustment; specify the capacity when you create the StringBuilder: StringBuilder result = new StringBuilder(str.Length); This will allocate a string with the exact right size. This has two advantages: 1. The StringBuilder never has to increase the capacity (which is done by allocating a new string with double the size, and copy the data from the previous string to it). 2. The string returned by the ToString method doesn't have any extra unused characters beyond the actual string. If you don't specify the length, the string may use up to twice as much memory as it needs to.

                    Experience is the sum of all the mistakes you have done.

                    1 Reply Last reply
                    0
                    • L Luc Pattyn

                      summing up to new string(Array.Reverse(original.ToCharArray()) or even better a sequence of original.ToCharArray(), Array.Reverse() and new string(char[]) :) -- modified at 15:58 Thursday 22nd November, 2007

                      Luc Pattyn [Forum Guidelines] [My Articles]


                      this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


                      G Offline
                      G Offline
                      Guffa
                      wrote on last edited by
                      #28

                      No, you can't do like that. The Array.Reverse method doesn't return the reversed array, it reverses the array in place.

                      Experience is the sum of all the mistakes you have done.

                      L 1 Reply Last reply
                      0
                      • G Guffa

                        No, you can't do like that. The Array.Reverse method doesn't return the reversed array, it reverses the array in place.

                        Experience is the sum of all the mistakes you have done.

                        L Offline
                        L Offline
                        Luc Pattyn
                        wrote on last edited by
                        #29

                        You're right of course. So I'd better turn it into a small method... :)

                        Luc Pattyn [Forum Guidelines] [My Articles]


                        this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


                        1 Reply Last reply
                        0
                        • I Imran Adam

                          Hi Guys i would like to know how you can create a simple method to return a string in reverse order. i have the following method public string myMethod (String myString) { . . //code goes in here . return myString } i have been trying to use a array to read the string into and try that but this doesnt seem to work any ideas please??

                          Cheers :)

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #30

                          Of course, as a quick and dirty hack you could always use a recursive method. I'm not saying you should, but you could. I've seen this done in so many homework assignments and coursework samples.

                          Deja View - the feeling that you've seen this post before.

                          My blog | My articles

                          G 1 Reply Last reply
                          0
                          • P Pete OHanlon

                            Of course, as a quick and dirty hack you could always use a recursive method. I'm not saying you should, but you could. I've seen this done in so many homework assignments and coursework samples.

                            Deja View - the feeling that you've seen this post before.

                            My blog | My articles

                            G Offline
                            G Offline
                            Guffa
                            wrote on last edited by
                            #31

                            The recursive method is pretty neat, actually. Who can resist a one-liner? ;) Not very efficient, though. :)

                            public string Reverse(string value) { return value.Length > 1 ? Reverse(value.Substring(1)) + value.Substring(0, 1) : value; }

                            Experience is the sum of all the mistakes you have done.

                            P 1 Reply Last reply
                            0
                            • L Luc Pattyn

                              Yep, just like a similar reverse problem[^] it can be solved with a single line of code, much shorter than each of the posts/replies in this thread... :)

                              Luc Pattyn [Forum Guidelines] [My Articles]


                              this months tips: - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use PRE tags to preserve formatting when showing multi-line code snippets


                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #32

                              What's a line of code?

                              1 Reply Last reply
                              0
                              • G Guffa

                                The recursive method is pretty neat, actually. Who can resist a one-liner? ;) Not very efficient, though. :)

                                public string Reverse(string value) { return value.Length > 1 ? Reverse(value.Substring(1)) + value.Substring(0, 1) : value; }

                                Experience is the sum of all the mistakes you have done.

                                P Offline
                                P Offline
                                Pete OHanlon
                                wrote on last edited by
                                #33

                                There you go then. The last step is to turn this into a delegate and you're laughing.

                                Deja View - the feeling that you've seen this post before.

                                My blog | My articles

                                G 1 Reply Last reply
                                0
                                • P Pete OHanlon

                                  There you go then. The last step is to turn this into a delegate and you're laughing.

                                  Deja View - the feeling that you've seen this post before.

                                  My blog | My articles

                                  G Offline
                                  G Offline
                                  Guffa
                                  wrote on last edited by
                                  #34

                                  Well, delegates can be used in many ways...

                                  public string Reverse(string value) {
                                  string result = string.Empty;
                                  new List(value.ToCharArray()).ForEach(delegate(char c) { result = c.ToString() + result; });
                                  return result;
                                  }

                                  ;)

                                  Experience is the sum of all the mistakes you have done.

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups