Thread: reverse function

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    30

    reverse function

    I am trying to reverse a string character by character. Here is what I have:
    Code:
    void reverseString( const char *str, char *wordreverse)
    {
    	int  i, j;
    	for( i = 0, j = strlen(str) - 1; i < j; i++, j--) {
    	      wordreverse[i] = str[j];
    
    
    	}
    	
    }
    The problem is the function only work on the last word because the space character is not copied to wordreverse. Can anyone help me fix it?
    Thanks
    Last edited by phoebus; 04-28-2008 at 08:54 PM.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Well.... what exactly are you trying to do? Reverse the characters in each word?

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    30
    If i have a string list this "this is a wonderful world" the reverse will be "dlrow lufrednow a si siht"

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Hmm.... what is the difference between str and wordreverse?

  5. #5
    Registered User
    Join Date
    Apr 2008
    Posts
    30
    not exactly but my professor doesn't want to change to orginal string so I have to use const char *str. then I can't change the orginal string, the wordreverse is an empty string use to store the reverse string of str.

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    i will only be less than j for half the string length: something you'd want if you were reversing a string in place through swapping. To create a reversed string you have to step through the string in reverse and copy each character.

  7. #7
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Check your condition. i<j is close but not correct.

    Edit: Beaten to it.

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    30
    Oh, I see now. Thank both of you for your comments.
    Last edited by phoebus; 04-28-2008 at 09:44 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. gethostbyaddr() reverse lookups failing (???)
    By Uncle Rico in forum C Programming
    Replies: 9
    Last Post: 08-19-2005, 09:22 AM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM