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

UK regulator has 'huge concerns' over Uber breachPosted on Wednesday November 22, 2017

A data breach affecting 57 million customers and drivers should not have been concealed, the information commissioner says.

Android phones 'betray' user location to GooglePosted on Wednesday November 22, 2017

The devices send location data back to Google even when location services are switched off.

Budget 2017: Funding for AI, 5G and digital skillsPosted on Wednesday November 22, 2017

The chancellor acknowledged the digital revolution would change the way people lived and worked.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×