Thread: How to reverse a string word by word?

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    56

    How to reverse a string word by word?

    So im just stared reading about pointers and would like to make a program to reverse a string word by word..

    I want to sweep backwards through the string using a pair of pointers to store last encounter word end and current position. then update the word end each time you reach the end of a word. and finally subtract the pointers to get a length.

    So i want to use fgets to get the string scanned into a array buffer, and use strchr to detect \0 on the string, but i cant figure out how to do it..

  2. #2
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    So this what you want -> want you what this So.
    Post the code you've written so far.

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main (void)
    {
      char buffer [1023];
      int len;
      char *end;
    
    
      printf ("Please enter a string: ");
      
      fgets(buffer,1023, stdin);
      len = (strlen(buffer));
      end = strchr(buffer,'\0');
      printf (end);
      printf ("Your reverse string is: ");
    //  for (; len >=0; len --)
    //    printf("%c", buffer[len]);
      
      
      printf("\n");
      return 0;
    }
    this is what i had on my screen, i been able to get the string reversed, letter by letter but not by word
    Last edited by SuperMiguel; 03-27-2012 at 06:13 PM.

  4. #4
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    also tried this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    void printReverse(char* string);
    int main(void)
    {
      printReverse("this is a test");
      return 0;
    
    
    }
    
    
    
    
    
    
    
    
    
    
    void printReverse(char* string) 
    {
    char* lastP = string;
    while (*string != NULL) 
    {
      if (*string == ' ') 
      {
        char* current = string -1;
        while (lastP != current) 
        {
          printf("%c", *current);
          current--;
        }
        printf("%c", *(current -1));
        lastP = string;
      }
      string++;
    }
    }
    but no go

  5. #5
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Okay, so what you need to do is break the string into words. Use strtok for this.
    Then store the individual words in an array, and print that array in reverse order.
    Code:
    while(!asleep) {
       sheep++;
    }

  6. #6
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    Quote Originally Posted by TheBigH View Post
    Okay, so what you need to do is break the string into words. Use strtok for this.
    Then store the individual words in an array, and print that array in reverse order.
    Thanks, ok i was able to get the words separated but i cant get them to print backwards.. this is what i got so far:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main (void)
    {
      char buffer [1023];
      char *split;
      char *inverse;
      char end;
      int i;
    
    
      printf ("Please enter a string: ");
      
      fgets(buffer,1023, stdin);
      split = strtok(buffer," ");
      end = strlen(split) - 1;
      for (i = 0; i < end ; i ++)
      {
        inverse[i] = split;
        //    printf("%s ", split);
        split = strtok (NULL, ", ");
      }
      for (i = end; i > 0; i--)
        printf("%s ", inverse[i]);
      return 0;
    }
    but i get a compiler error

    Code:
    reverseWords.c: In function ‘main’:
    reverseWords.c:19: warning: assignment makes integer from pointer without a cast
    reverseWords.c:24: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
    reverseWords.c:24: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’

  7. #7
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Use strcpy to copy the results of strtok into your strings:
    Code:
    strcpy( split, strtok( buffer, " " ) );
    To do this you will need to change "split" from a char* to an array of chars.

    Your other problem now is that "inverse" is just one string. You need it to be an array of strings, ie. an array of arrays of characters.
    Code:
    char inverse[MAX_NUMBER_OF_WORDS][MAX_LETTERS_PER_WORD];
    Then inverse[i] represents the ith word, and inverse[i][j] represents the jth character of the ith word.
    Code:
    while(!asleep) {
       sheep++;
    }

  8. #8
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    why would i care about the jth caracter??

    like if i do

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main (void)
    {
      char buffer [1023];
      char *split;
    //  char inverse[1023];
    //  char end;
    //  int i = 0;
    //  int x;
    
    
      printf ("Please enter a string: ");
      
      fgets(buffer,1023, stdin);
      split = strtok( buffer, " ");
    //  end = strlen(split) - 1;
      while (split != NULL)
      {
    //    inverse [i] = split;
        printf("%s \n", split);
        split = strtok (NULL, ", ");
      }
      return 0;
    }
    I get a list of my input, i just need to reverse that list
    Code:
    Please enter a string: This is a test
    This 
    is 
    a 
    test
    Last edited by SuperMiguel; 03-27-2012 at 10:34 PM.

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    347
    i tried to attempt the program which reverses the words and this my version of code but it fails in the last for loop where it unexpectedly closes the window.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
    
        char array[100];
        char *pch;
        char *reverse[20];
        unsigned char index=0;
        unsigned char i=0;
    
        printf("Enter the string\n");
        fgets(array,100,stdin);
        pch = strtok (array," ");
        reverse[index++] = pch;
    
        while (pch != NULL)
         {
           printf ("%s\n",pch);
           pch = strtok (NULL, " ");
           reverse[index++] = pch;
         }
        index--;
    
       for(i=index-1; i >= 0; i-- )
            printf("%s",reverse[i]);
    
        return 0;
    }
    could somebody help me why is it happening like this?

    thanks and regards,
    satya

  10. #10
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    im almost there:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main (void)
    {
      char buffer [1023];
      char *split;
      char *inverse[1023];
    //  char end;
       int i = 0;
       int x = 0;
    
    
      printf ("Please enter a string: ");
      
      fgets(buffer,1023, stdin);
      split = strtok( buffer, " ");
    //  end = strlen(split) - 1;
      while (split != NULL)
      {
        inverse[i] = split;
    //    printf("%s \n", split);
        split = strtok (NULL, ", ");
        i++;
      }
      for (;x <= 0; i--)
      printf("%s \n", inverse[i]);
      return 0;
    }
    Not sure why im getting the seg fault
    Code:
    Please enter a string: This is a test
    (null) 
    test
     
    a 
    is 
    This 
    Segmentation fault: 11

  11. #11
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    I think your for loop in line 27 is not right yet. Did you mean
    Code:
    for (;i >= 0; i--)
    ?
    Code:
    while(!asleep) {
       sheep++;
    }

  12. #12
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    got it
    Last edited by SuperMiguel; 03-28-2012 at 08:42 AM.

  13. #13
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    When you print out the results i is one index after the last word. This is because your loop logic is a bit funny.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  14. #14
    Registered User
    Join Date
    Mar 2012
    Posts
    56
    got it
    Last edited by SuperMiguel; 03-28-2012 at 08:42 AM.

  15. #15
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    That's because when you are tokenizing you are only tokenizing based on spaces ' '. Therefore, the endline '\n' becomes a separate word. Include \n in your tokenization identifiers string.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 28
    Last Post: 10-23-2011, 07:17 PM
  2. reading text-and-numbers file word by word
    By bored_guy in forum C Programming
    Replies: 22
    Last Post: 10-26-2009, 10:59 PM
  3. reverse a word
    By hope in forum C Programming
    Replies: 1
    Last Post: 09-17-2008, 07:42 AM
  4. open file, search of word, replace word with another
    By Unregistered in forum C++ Programming
    Replies: 0
    Last Post: 06-05-2002, 01:16 PM
  5. Help reading text file word by word
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 05-25-2002, 05:13 PM