Thread: String Reversal (kinda different from the rest)

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    1

    String Reversal (kinda different from the rest)

    Hello, I'm new to C, and I had a question about reversing a string. I have my code to print it in reverse, but what im looking to do is actually reverse the string in memory. This is what i have so far.Any ideas?
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
      char string[80];
      int size;
    
      printf("Enter String: ");
      scanf("%s", string);
      size = strlen(string);
      
      while (size >= 0) {
        printf("%c", string[size]);
        size--;
      }
    
      return 0;
    }

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>Any ideas?
    Plenty. Some you'll be interested in, some you won't.
    You've provided code that prints the string in reverse, so what have you tried for the in-memory reversing?

    You need to learn to swap characters within the array. Try drawing out on paper, and think about how you'd do it, then try to translate that into code.

    Code:
    This is a string\0
    012345678901234567
    
    1 - Swap number X with number Y
    2 - Swap number Z with number W
    etc
    etc
    To do the swapping, you'll need a third char, to act as a temporary holder.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Lets take a look at one way:
    "Hello World"
    If we switch the first and last letter we get
    "dello WorlH"
    now if we move inward one position and do it agan we get
    "dlllo WoreH"
    If we keep doing this we get
    dlrlo WoleH
    dlroo WlleH
    dlroW olleH

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    scanf() isn't the best choice of functions for getting a string from the user. fgets() would be better. Also, your printf() is printing a '\0' as the first character. Not detrimental I guess, but it doesn't do much.
    If you understand what you're doing, you're not learning anything.

  5. #5
    Registered User xxxrugby's Avatar
    Join Date
    Jan 2005
    Posts
    178
    You can use this for enter strings so you dont have to use scanf and gets

    Code:
      while( (ch = getchar()) != '\n')
      {
             string[i] = ch;
             i++;
      }
    Sorry for spelling errors, not English!
    xxxrugby: "All Human Race Will Die From My Hand!"
    xxxrugby: "We are all philosophers, when question is about politics!"

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >You can use this for enter strings so you dont have to use scanf and gets
    And yet, that has precisely the same problems as scanf and gets (and more). Why not just use fgets and be done with it?
    My best code is written with the delete key.

  7. #7
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    using something like bubble sort will do your swap, but keep in mind that with bubble sort, in the worst case you will get the max of inversions that need to be made.
    When no one helps you out. Call google();

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Quote Originally Posted by InvariantLoop
    using something like bubble sort will do your swap, but keep in mind that with bubble sort, in the worst case you will get the max of inversions that need to be made.
    What does bubble sort have to do with reversing the order of a string? That sounds like a huge leap in the wrong direction, even though the principles of sorting can be used toward reversing a string if you think about it all squiggly.
    My best code is written with the delete key.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You could bubble sort, using the memory addresses as the comparison. I have no idea why you would want to, but it would work.

    [edit] Hm... It would be interesting to do it that way. It would take quite a bit of work. You'd have to map the address to the character itself. It's definately warped. I may have to try it... [/edit]

    Quzah.
    Last edited by quzah; 02-16-2005 at 08:19 AM.
    Hope is the first step on the road to disappointment.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >It would take quite a bit of work.
    Not really. Just add ampersands in the test and you're done. It's somewhat interesting, but far more interesting is getting it to work generally. For example, how do you know whether an implementation stores the string with ascending or descending memory addresses? One would reverse correctly and the other would do nothing. Also more interesting would be a performance analysis. For a general function, would the performance boost of comparing large objects by address rather than by value be worth the extra work of getting the sort right? What if the objects are small, such as characters?
    My best code is written with the delete key.

  11. #11
    verbose cat
    Join Date
    Jun 2003
    Posts
    209
    Quote Originally Posted by quzah
    You could bubble sort, using the memory addresses as the comparison. I have no idea why you would want to, but it would work.

    [edit] Hm... It would be interesting to do it that way. It would take quite a bit of work. You'd have to map the address to the character itself. It's definately warped. I may have to try it... [/edit]

    Quzah.
    Still thinking about obfuscating code, eh?
    abachler: "A great programmer never stops optimizing a piece of code until it consists of nothing but preprocessor directives and comments "

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Prelude
    For example, how do you know whether an implementation stores the string with ascending or descending memory addresses?
    I'd like to see on that stored it in descending order. It goes against the grain:
    Code:
    char *ptr1, *ptr2;
    
    ptr1 = passedstring;
    ptr2 = strlen( ptr1 ) + ptr1;  /* now we point at the null */
    I can't really envision one that would store in backwards, because the very basics of string manipulation would immediately become broken.

    Still, if such a case did exist, all you'd have to do is one simple test:
    Code:
    if( ptr1 > ptr2 )
    {
        printf( "Your implementation is ass-backwards.\n" );
    }
    And deal with it from there by reversing the swap order.

    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by jEssYcAt
    Still thinking about obfuscating code, eh?
    It's just a really messed up way of doing something, so it became interesting.

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Something like this?
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void revstr(char *str)
    {
    
      struct str_s
      {
        char ch;
        char *ptr;
      } strarray[strlen(str)], temp;
      int len, i, j;
    
      for(len = 0;str[len];++len)
      {
        strarray[len].ch = str[len];
        strarray[len].ptr = str+len;
      }
    
      for(i = 0;i < len;++i)
        for(j = i+1;j < len;++j)
          if(strarray[i].ptr < strarray[j].ptr)
          {
            memcpy(&temp, &strarray[i], sizeof(struct str_s));
            memcpy(&strarray[i], &strarray[j], sizeof(struct str_s));
            memcpy(&strarray[j], &temp, sizeof(struct str_s));
          }
    
      for(i = 0;i < len;++i)
        str[i] = strarray[i].ch;
      str[i] = '\0';
    }
    
    int main(void)
    {
      char str[] = "abcdefg";
    
      printf("String: %s\n", str);
      revstr(str);
      printf("Reversed: %s\n", str);
    
      return 0;
    }
    Code:
    itsme@dreams:~/C$ ./revstr
    String: abcdefg
    Reversed: gfedcba
    If you understand what you're doing, you're not learning anything.

  15. #15
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Dealing with the first half of the thread:
    Snippets anyone?
    > http://www.cprogramming.com/snippets...ount=30&page=0
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 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
  2. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM