Write a C program to reverse the order of words in a string?

How to reverse the order of words in a text string is a frequently asked interview question. The application use of this problem is that if there are two words separated by a space, a typical example is "LastName FirstName". Then reversing the order of words will arrange them like "FirstName LastName".

Reversing the order of words in a string is two step solution:

  1. First, reverse the string by swapping the first character with the last character, the second character with the second-to-last character, and so on.
  2. Then, go through the string looking for spaces, so that you find where each of the words is. Reverse each of the words you encounter by again swapping the first character with the last character, the second character with the second-to-last character, and so on.

The following piece of code reverses the order of words in given string. For demonstration purpose, the string is hard-coded in the code itself; while in real world input will be taken either from keyboard or file.

#include <stdio.h>
#include <string.h>
#define MAXLEN 100
 
void reverseString(char*, int, int);
void reverseWords(char*, int);
int main()
{
  char string[MAXLEN] = "Kumar Krishan";
  printf("Input String: %s\n", string);
  reverseString(string, 0, strlen(string) - 1);
  reverseWords(string, strlen(string));
  printf("Output String: %s\n", string);
}
 
void reverseString(char* buffer, int startIndex, int endIndex)
{
 
  int ch, i, j;
  for (i = startIndex, j = endIndex; i < j; i++, j--)
  {
    ch = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = ch;
  }
}
 
void reverseWords(char* buffer, int strLength)
{
  if (*buffer == '\0') // check for null
    return;
 
  // extract a word from the buffer and reverse it
  // to get back the original word.
  int startWord = 0, endWord = 0;
  while (endWord < strLength)
  {
    While (buffer[endWord] != ' ' && buffer[endWord] != '\0')
    {
      endWord++;
    }
    reverseString(buffer, startWord, endWord-1);
    startWord = ++endWord;
  }
}
 
OUTPUT
======
[krishan@localhost ~/cprogs]$ gcc rev_order.c -o rev_order
[krishan@localhost ~/cprogs]$ ./rev_order
Input String: Kumar Krishan
Output String: Krishan Kumar

Above C program has two functions viz reverseString and reverseWords. Both are quite straight forward. Function reverseString reverses the string; whereas reverseWords reverses individual words in a string. This program is just for demonstrating how to reverse the order of words in a string and tackles only single space to delimit words, new-line and tabs are not handled here.

Hope you have enjoyed reading this answer for reversing the order of words in a string. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

WannaCry ransom notice analysis suggests Chinese linkPosted on Monday May 29, 2017

Researchers say the WannaCry ransom note was poorly translated - possibly using Google Translate.

BA boss 'won't resign' over flight chaosPosted on Monday May 29, 2017

Chief executive Alex Cruz says flight disruption at Heathrow and Gatwick had nothing to do with cost cutting.

Hay Festival 2017: Stephen Fry's warning for the webPosted on Sunday May 28, 2017

Delivering a lecture at the Hay Festival, the actor said society could face "dire consequences".

Courtesy BBC News