Thread: How to NOT reverse a string in place.

  1. #1
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195

    How to NOT reverse a string in place.

    The way I understand reversing a string in place is that when you reverse a string, you modify the original. On the other end, when you don't reverse a string in place, you use more memory, but still have the original string. Maybe I'm being really stupid on this, but I don't see how the latter can be done.

    Even if I go something like

    Code:
    void reverse (char s[]) {
    /*code*/
    }
    
    int main(void) {
    char buffer[] = "stringy";
    reverse(buffer);
    return 0;
    }
    I still modify buffer (ie no longer have the original string).

  2. #2
    Sys.os_type="Unix";;
    Join Date
    Aug 2005
    Posts
    52
    Get the length of the string - 1.
    And just implement that into a for loop with another variable initialized to 0 and increment that while decrementing the length.
    Using a temp variable you can just work your way through the string.

    That's the K&R way to reverse a char array but you end up modifying the original.


    To save the original... then just don't use it write up a function expecting a pointer to the original and a pointer to the destination.
    Get the strlen of the original - 1. move the dest pointer that amount and just work your way through each at the same time within a loop.


    Although it would be the same as copying the original to another and then reverse the second.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195
    Okay, I had to re-read that response a few times before it sunk in. But what you said works.

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. reverse a string in place
    By anjana in forum C Programming
    Replies: 3
    Last Post: 10-10-2006, 05:30 AM
  4. Replies: 7
    Last Post: 03-18-2003, 03:32 PM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM