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

Robotic barman pours Rory a pintPosted on Friday March 24, 2017

The BBC’s technology correspondent Rory Cellan-Jones gets a beer poured for him by a robotic barman - but how long does it take?

Row over US ISP customer data salesPosted on Friday March 24, 2017

US politicians have voted to let ISPs gather and sell data about what Americans do online.

Ofcom plans instant payback for broadband woesPosted on Friday March 24, 2017

Customers who suffer poor service could get automatic payouts under Ofcom's plan.

Courtesy BBC News