Reverse order of words in a string using C language

Graphic showing typeset

Reversing the order of words in a string is a common interview question for embedded software engineer jobs. The idea of this example C program is to reverse the order of words but not the characters of the string. Description and code walk-through is also explained in this article.

Example:
Input: “Hello world”
Output: “world Hello”

Code walk-through

The function wordReverse() reverses the word in the given string. The temporary variable int wordStart = 0; is used to keep track of the character position of the start of a word. In the below line,

all characters in the string str is reversed by the helper function reverse().

The below lines will reverse the words alone,

After completing the above step, the words in the given string are reversed (a second reversal on the already reversed word characters will have the original word recreated).

Notes on the helper function reverse()

This function will reverse the string characters by dividing the string to half and swapping the end characters and repeats until all the characters are swapped resulting in reversal of the given string.


Leave a Reply 0

Your email address will not be published. Required fields are marked *