Thread: reverse words

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    9

    reverse words

    Hi all,

    This C program reverses the first n words in a string, for example:
    echo "hello world do not reverse" | rev 2 should output:
    "world hello do not reverse"
    Here's my code:
    Code:
     
           1 #include <stdio.h>
          2 #include <stdlib.h>
          3 #include <ctype.h>
          4 #include <string.h>
          5
          6 void swap(char* str, int i, int j) {
          7    char t = str[i];
          8    str[i] = str[j];
          9    str[j] = t;
         10 }
         11
         12 void reverse_string(char* str, int length) {
         13    int i;
         14    for (i = 0; i < length / 2; i++)
         15       swap(str, i, length - i  - 1);
         16 }
         17
         18 int main(int argc, char *argv[]) {
         19    char str[1024];
         20    char chars[1024];
         21    int l;
         22    int p;
         23    int i;
         24     if (argc != 2) {
         25        printf("Invalid argument");
         26        return 1;
         27     }
         28     if (atoi(argv[1]) <= 0) {
         29        printf("Invalid argument");
         30        return 2;
         31     }
         32     str[0] = '\0';
         33     while (fgets(chars, 1024, stdin))
         34        strcat(str, chars);
         35     l = strlen(str);
         36     reverse_string(str, l);
         37     p = 0;
         38     for(i = 0; i < l; i++) {
         39        if(str[i] == ' ') {
         40           reverse_string(&str[p], i - p);
         41           p = i + 1;
         42        }
         43     }
         44     reverse_string(&str[p], l - p);
         45     printf("%s\n", str);
         46     return 0;
         47 }
    The above code should reverse all the words in the string. How can I modify the code so it'll be for the first n words only?

    Thanks in advance

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Walk through the string until you find a space character then increment a variable counter until it equals n, then you can reverse those words. just an idea im sure there are many better ways to go about doing this.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    in the line 35 instead of strlen call your own function that will return length in chars of the first n words you are going to reverse
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    9
    How?

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by ydan87 View Post
    How?
    I would use a 2 dimension char array[50][50], and set it to all '\0' (NULL char's).

    Now put each word in the line of text, into it's own row of the array[0], is the first word, (a pointer to it), and array[1], is the address of the second word, etc.

    Get all the words, so you can reconstruct the full line of text. Send the first N words to the reverse string function to have them reversed.

    You have some good code there, unfortunately, you didn't write it, and now it has to be changed a bit. This is probably exactly what your teacher wanted to happen.

    In programming, the details are important to the overall design of the program, and the code you have, is not exactly right.

    The above is the simplest way I know of, to do this.

  6. #6
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    If you understand how and why the above program accomplishes reversing the string word-by-word and not just the reverse of the whole string, then you'll see how simple it is to reverse only the first n words of the string. It basically comes down to figuring out where the end of the nth word is in the string.

  7. #7
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Recursion its another option:
    Code:
    void rev(char *o,char *s,int i)
    {
      char t[100];
      int n;
      if( i-- && 1==sscanf(s,"%s%n",t,&n) )
      {
        rev(o,s+n,i);
        if(*o)
          strcat(o," ");
        if(o==s)
          memcpy(o+strlen(o),t,strlen(t));
        else
          strcat(o,t);
      }
      else
        *o=0;
    }
    
    
    int main()
    {
      char s[]="three two one four five";
      rev(s,s,3);  /* reverve first 3 words */
      puts(s);
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reverse words in string
    By perrrson in forum C Programming
    Replies: 3
    Last Post: 10-26-2010, 07:01 AM
  2. reverse the words sorting in a string
    By St0rM-MaN in forum C Programming
    Replies: 17
    Last Post: 06-18-2007, 10:31 AM
  3. Replies: 7
    Last Post: 03-18-2003, 03:32 PM
  4. reverse words in a string
    By kenni81 in forum C Programming
    Replies: 14
    Last Post: 02-05-2003, 11:52 AM
  5. Reverse words
    By Dr. Bebop in forum C Programming
    Replies: 4
    Last Post: 09-09-2002, 09:05 AM