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

    That was a topic in here some time in the last year, do you want to search for it or shall I?

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

    last year? thats too long time ago. i go back a lil, but not that far. could u please search n let me know, that would be v.helpful

    Cheers :)

    P 2 Replies 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 :)

      J Offline
      J Offline
      J4amieC
      wrote on last edited by
      #4
      I 1 Reply Last reply
      0
      • J J4amieC
        I Offline
        I Offline
        Imran Adam
        wrote on last edited by
        #5

        BTW this is not my Homework, i have written the lines needed to reverse and display the string in the console. but i cant manage to RETURN a REVERSED String!!

        Cheers :)

        A I P J 4 Replies Last reply
        0
        • I Imran Adam

          BTW this is not my Homework, i have written the lines needed to reverse and display the string in the console. but i cant manage to RETURN a REVERSED String!!

          Cheers :)

          A Offline
          A Offline
          Anthony Mushrow
          wrote on last edited by
          #6

          If you can reverse the string and display it in a console, then it should be pretty easy to return the reversed string.

          My current favourite word is: PIE! Good ol' pie, it's been a while.

          1 Reply Last reply
          0
          • I Imran Adam

            BTW this is not my Homework, i have written the lines needed to reverse and display the string in the console. but i cant manage to RETURN a REVERSED String!!

            Cheers :)

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

            can anyone help me please ??

            Cheers :)

            1 Reply Last reply
            0
            • I Imran Adam

              BTW this is not my Homework, i have written the lines needed to reverse and display the string in the console. but i cant manage to RETURN a REVERSED String!!

              Cheers :)

              P Offline
              P Offline
              pmarfleet
              wrote on last edited by
              #8

              Where is this code? You didn't provide it in your original post. If you have already managed to reverse the string and display it, you must have the reversed string in a variable to be returned from your method. The absence of this code suggests that you haven't written it at all and want someone else to do it for you. This isn't how the site works.

              Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush

              I 1 Reply Last reply
              0
              • I Imran Adam

                BTW this is not my Homework, i have written the lines needed to reverse and display the string in the console. but i cant manage to RETURN a REVERSED String!!

                Cheers :)

                J Offline
                J Offline
                J4amieC
                wrote on last edited by
                #9

                As just stated, if its not homework and you have working code then post it and someone here will explain the use of the return keyword for you. I still call this out as homework.

                L 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 :)

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #10

                  hmmmm... does that sound like a homework question? you could use a stack to do this:

                  public void Main()
                  {
                  string foo = "i will do my homework on my own";
                  string blah = reverseString(foo);
                  Console.WriteLine(foo);
                  Console.WriteLine(blah);
                  }
                  public void reverseString(string Text)
                  {
                  System.Collections.Stack st = new Stack();
                  foreach (char c in Text)
                  {
                  st.Push(c);
                  }
                  ArrayList l = new ArrayList();
                  while (st.Count > 0)
                  {
                  l.Add(st.Pop());
                  }
                  char[] s = l.ToArray(typeof(char)) as char[];
                  string RetVal = new string(s);
                  return RetVal;
                  }

                  but if you use one of the other 999999999 possibilities to do it it'll be more efficient

                  I S 2 Replies Last reply
                  0
                  • P pmarfleet

                    Where is this code? You didn't provide it in your original post. If you have already managed to reverse the string and display it, you must have the reversed string in a variable to be returned from your method. The absence of this code suggests that you haven't written it at all and want someone else to do it for you. This isn't how the site works.

                    Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush

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

                    OMG... ok then, i created a char array; char[] myArray = new char[m]; //m is the length of array read all the data into the array using; for (int i =0; iCheers :)

                    1 Reply Last reply
                    0
                    • L Lost User

                      hmmmm... does that sound like a homework question? you could use a stack to do this:

                      public void Main()
                      {
                      string foo = "i will do my homework on my own";
                      string blah = reverseString(foo);
                      Console.WriteLine(foo);
                      Console.WriteLine(blah);
                      }
                      public void reverseString(string Text)
                      {
                      System.Collections.Stack st = new Stack();
                      foreach (char c in Text)
                      {
                      st.Push(c);
                      }
                      ArrayList l = new ArrayList();
                      while (st.Count > 0)
                      {
                      l.Add(st.Pop());
                      }
                      char[] s = l.ToArray(typeof(char)) as char[];
                      string RetVal = new string(s);
                      return RetVal;
                      }

                      but if you use one of the other 999999999 possibilities to do it it'll be more efficient

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

                      ok this is my method, the loop is not functioning, but i cant see y??? public string Reverse(string WhatToReverse) { int lengthOfArray = WhatToReverse.Length; //char array char[] myArray = new char[lengthOfArray]; for (int i = lengthOfArray; i < 0; i--) { myArray[i] = WhatToReverse[i]; Console.Write(myArray[i]); } return ;//still to complete, but the loop dont work }

                      Cheers :)

                      J 1 Reply Last reply
                      0
                      • I Imran Adam

                        last year? thats too long time ago. i go back a lil, but not that far. could u please search n let me know, that would be v.helpful

                        Cheers :)

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

                        Here's one: http://www.codeproject.com/lounge.asp?searchkw=reversing+string&sd=24+Aug+2006&ed=22+Nov+2007&stype=1&select=2146010&df=100&forumid=1159&exp=1&mpp=50&fr=3047[^]

                        L 1 Reply Last reply
                        0
                        • I Imran Adam

                          ok this is my method, the loop is not functioning, but i cant see y??? public string Reverse(string WhatToReverse) { int lengthOfArray = WhatToReverse.Length; //char array char[] myArray = new char[lengthOfArray]; for (int i = lengthOfArray; i < 0; i--) { myArray[i] = WhatToReverse[i]; Console.Write(myArray[i]); } return ;//still to complete, but the loop dont work }

                          Cheers :)

                          J Offline
                          J Offline
                          Jason Lepack LeppyR64
                          wrote on last edited by
                          #14

                          hustler2005 wrote:

                          for (int i = lengthOfArray; i < 0; i--)

                          I is not less than 0 at the start.

                          1 Reply Last reply
                          0
                          • J J4amieC

                            As just stated, if its not homework and you have working code then post it and someone here will explain the use of the return keyword for you. I still call this out as homework.

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

                            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 1 Reply Last reply
                            0
                            • I Imran Adam

                              last year? thats too long time ago. i go back a lil, but not that far. could u please search n let me know, that would be v.helpful

                              Cheers :)

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

                              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 1 Reply Last reply
                              0
                              • P PIEBALDconsult

                                Here's one: http://www.codeproject.com/lounge.asp?searchkw=reversing+string&sd=24+Aug+2006&ed=22+Nov+2007&stype=1&select=2146010&df=100&forumid=1159&exp=1&mpp=50&fr=3047[^]

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

                                I must object a little; in C# strings are immutable, so swapping chars isn't the right way...

                                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
                                • L Lost User

                                  hmmmm... does that sound like a homework question? you could use a stack to do this:

                                  public void Main()
                                  {
                                  string foo = "i will do my homework on my own";
                                  string blah = reverseString(foo);
                                  Console.WriteLine(foo);
                                  Console.WriteLine(blah);
                                  }
                                  public void reverseString(string Text)
                                  {
                                  System.Collections.Stack st = new Stack();
                                  foreach (char c in Text)
                                  {
                                  st.Push(c);
                                  }
                                  ArrayList l = new ArrayList();
                                  while (st.Count > 0)
                                  {
                                  l.Add(st.Pop());
                                  }
                                  char[] s = l.ToArray(typeof(char)) as char[];
                                  string RetVal = new string(s);
                                  return RetVal;
                                  }

                                  but if you use one of the other 999999999 possibilities to do it it'll be more efficient

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

                                  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 1 Reply Last reply
                                  0
                                  • 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
                                          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