You are here

C program to reverse words in a string

C program to reverse words in a string or sentence, for example, if the input string is "c++ programming language" then the output will be "++c gnimmargorp egaugnal" i.e. we will invert each word occurring in the input string. Algorithm is very simple just scan the string and keep on storing characters until a space comes. If a space is found then we have found one word so we append null terminator and then reverse the word and then copy the characters of original string with the string obtained on reversing. Then repeat the previous step until the string ends.

C programming code

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void reverse_string(char*);
  5. void reverse_words(char*);
  6.  
  7. int main() {
  8.   char a[100];
  9.  
  10.   gets(a);
  11.  
  12.   reverse_words(a);
  13.  
  14.   printf("%s\n", a);
  15.  
  16.   return 0;
  17. }
  18.  
  19. void reverse_words(char *s) {
  20.   char b[100], *t, *z;
  21.   int c = 0;
  22.  
  23.   t = s;
  24.  
  25.   while(*t) {                           //processing complete string
  26.     while(*t != ' ' && *t != '\0') {    //extracting word from string
  27.       b[c] = *t;
  28.       t++;
  29.       c++;
  30.     }
  31.     b[c] = '\0';
  32.     c = 0;
  33.  
  34.     reverse_string(b);        // reverse the extracted word
  35.  
  36.     z = b;
  37.  
  38.     while (*z) {    //copying the reversed word into original string
  39.       *s = *z;
  40.       z++;
  41.       s++;
  42.     }
  43.  
  44.     while (*s == ' ') {                 // skipping space(s)
  45.       s++;
  46.     }
  47.     /*
  48.      * You may use if statement in place of while loop if
  49.      * you are assuming only one space between words. If condition is
  50.      * used because null terminator can also occur after a word, in
  51.      * that case we don't want to increment pointer.
  52.      * if (*s == ' ') {
  53.      *   s++;
  54.      * }
  55.      */
  56.     t = s;                              // pointing to next word
  57.   }
  58. }
  59.  
  60. /*
  61.  * Function to reverse a word.
  62.  */
  63.  
  64. void reverse_string(char *t) {
  65.   int l, c;
  66.   char *e, s;
  67.  
  68.   l = strlen(t);
  69.   e = t + l - 1;
  70.  
  71.   for (c = 0; c < l/2; c++) {
  72.     s  = *t;
  73.     *t = *e;
  74.     *e = s;
  75.     t++;
  76.     e--;
  77.   }
  78. }

Download Reverse words program.

Output of program:
Reverse words c program