Thread: Easy way to reverse a string

  1. #1
    Slime Dragoon_42's Avatar
    Join Date
    Feb 2003
    Location
    Vancouver
    Posts
    90

    Easy way to reverse a string

    What is the easiest way to reverse a sting? I thought there was a function, but I cannot remember it. Is there a page that lists all functions of all classes I could look at?

  2. #2
    Registered User
    Join Date
    Mar 2003
    Posts
    134
    easy way would be to copy is to use a loop and some functions from the string header file

    http://www.cplusplus.com/ref/cstring/

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >What is the easiest way to reverse a sting?
    If your compiler supports strrev or anything similar then that's the easiest way. Otherwise, a loop that walks from either end of the string toward the middle and swaps until the two indices are the same would come a close second.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Mar 2003
    Posts
    134
    Here is an implementation of strrev
    http://64.233.167.104/search?q=cache...hl=en&ie=UTF-8

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You could easily implement one yourself, e.g.
    1. Iterate from the last character to the first, placing them into a new string.
    2. Swap the nth character with the (length - n)th character.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Here is an implementation of strrev
    A good example of the programmer trying to be clever...
    My best code is written with the delete key.

  7. #7
    Registered User
    Join Date
    Mar 2003
    Posts
    134
    huh Prelude ????

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >huh Prelude ????
    I was just commenting on this:
    Code:
    *p1 ^= *p2;
    *p2 ^= *p1;
    *p1 ^= *p2;
    It's cute, but shouldn't be used in any real code without an exceptionally good reason. It's hard to use correctly, and very few people understand the nuances.
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Mar 2003
    Posts
    134
    aha

  10. #10
    Slime Dragoon_42's Avatar
    Join Date
    Feb 2003
    Location
    Vancouver
    Posts
    90
    Wow. Thanks for all the help! I thought there was a built in function, but aparrently my GCC compiler does not support it. So I just wrote my own:
    Code:
    char* reverse_str(char *m)/*reflects rotor*/
    {
    	char rev[26];
    	strcpy(rev,m);/*stores rotor for reversal*/
    	unsigned length=strlen(m);
    	unsigned count;/*counter for string reversal*/
    	for(count=0;count<length;count++)
    	{
    		m[count]=rev[length-count];
    	}
    	return m;
    }
    BTW, what does the ^= operator do?
    Last edited by Dragoon_42; 04-16-2004 at 10:09 AM. Reason: Forgot a question

  11. #11
    Registered User
    Join Date
    Dec 2003
    Posts
    92
    hi dragon, i am following this topic. i got segmentation fault while calling your reverse_str function.

    my main code:
    Code:
    int main()
    {
    char*s ;
    s = reverse_str("mango");
    printf("%s",s);
    
    }

    output > segmentation fault

    why ??


    another question, what is unsigned ?? it should be unsigned int. r u sure ur code is ok ?

    N.B : is it not necesarry to null terminate inside ?
    blue_gene

  12. #12

    Post

    Hi all,

    Just for my opinion, and the nice implentation, I'd definetly go for the strrev() code. It's really nice in my opinion, and it worked perfectly first time I compiled it:

    Code:
    #include <stdlib.h> // for printf
    
    char* my_strrev(char *);
    
    char* my_strrev(char *string1) {
    	char *p1, *p2;
    
    	if (!string1 || !*string1)
    		return string1;
    
    	for (p1 = string1, p2 = string1 + strlen(string1) - 1; p2 > p1; ++p1, --p2) {
    		*p1 ^= *p2;
    		*p2 ^= *p1;
    		*p1 ^= *p2;
    	}
    
    	return string1;
    }
    
    int main () {
    	char str[256] = {"!looc si sihT"};
    
    	printf("%s\n", my_strrev(str) ); // call on function in here for ex.
    
    	return 0;
    }
    Code 1.1: Using my_strrev()

    Now I only called the function my_strrev() because any previous header file or DLL linkage might try figthing over which function to use and etc...

    I take my hat off to noob2c for finding this function I'm making a replica of the string library, so many thanks, I'll have to add this implementation to my project.

    Edit (after noob2c post): Ah, ok. Much thanks to you too Prelude


    Hope this helps,
    - Stack Overflow
    Last edited by Stack Overflow; 04-16-2004 at 12:14 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  13. #13
    Registered User
    Join Date
    Mar 2003
    Posts
    134
    no problem..... it was prelude who knew the name of the function .... i did a search to find it. As for ^= that means exclusive or or XOR

  14. #14
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Exclusive OR (XOR) returns true only when the two values are different.
    Truth table for XOR:
    Code:
       0 1
    0| 0 1
    1| 1 0
    ^ is a bitwise XOR so if you have:
    1010 and 1101 you would get: 0111

  15. #15
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    I always prefer to take the easist route until I'm sure of what is going on. As such I would recommend what Prelude suggest and avoid the codes that use ^= until you are 125% sure you know what it is doing.

    Below is a quicky I threw together that uses 0 tricks and should be easy enough to walk through. Hope it is of help:
    Code:
    char *strrev(char *str)
    {
      unsigned len = strlen(str) - 1; /* Minus one so we don't move the null character */
      int count;
      char ch;
      for (count=0; count < len; count++, len --)
      {
        ch = str[count];
        str[count] = str[len];
        str[len] = ch;
      }
    
      return str;
    }
    A test program could look like this:
    Code:
    #include <stdio.h>
    int main (void)
    {
      char msg1[]="Hello my baby hello my darling hello my ragtime gal!";
      char msg2[]="Save me a kiss by wire, baby my heart is on fire!";
    
      puts("Before");
      puts(msg1);
      puts(msg2);
      puts("After");
      puts(strrev(msg1));
      puts(strrev(msg2));
    
      return 0;
    }
    Note: Changing the declaration of msg1 and msg2 from char [] to char * will result in a segmentation fault since that area of memory will be marked as read only.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  2. Reverse a string (without using any string functions?)
    By geetard in forum C Programming
    Replies: 2
    Last Post: 11-15-2006, 07:42 PM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  4. Replies: 7
    Last Post: 03-18-2003, 03:32 PM
  5. Overflowing string... any easy way to fix it?
    By Trauts in forum C++ Programming
    Replies: 2
    Last Post: 11-26-2002, 08:35 PM