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”
#include <stdio.h>int reverse(char *str);int swap(char *x, char *y);int wordReverse(char *str);int main(){char name[100] = "hello world";wordReverse(name);printf("%s\n", name);return 0;}int reverse(char *str){int retVal = -1;int i = 0;int j, x;if (str != (void *)0){retVal = 0;while (*(str + i)){i++;}i--;x = (i / 2) + 1;for (j = 0; j < x; j++, i--){(void)swap(str + j, str + i);}}return retVal;}int swap(char *x, char *y){int retVal = -1;char temp;if (x != (void *)0 || y != (void *)0){retVal = 0;temp = *x;*x = *y;*y = temp;}return retVal;}int wordReverse(char *str){int retVal = -1;int i = 0;int wordStart = 0;if (str != (void *)0){retVal = 0;(void)reverse(str);while (*(str + i)){if (*(str + i) == ' '){*(str + i) = '\0'; // Replacing space with null character(void)reverse(str + wordStart);*(str + i) = ' '; // Reverting the space characterwordStart = i + 1;}i++;}(void)reverse(str + wordStart);}return retVal;}
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,
(void)reverse(str);
all characters in the string str is reversed by the helper function reverse().
The below lines will reverse the words alone,
while (*(str + i)) // Iterates the entire string{if (*(str + i) == ' ') // If a space character is found, then reverse the word{*(str + i) = '\0'; // Replacing space with null character(void)reverse(str + wordStart);*(str + i) = ' '; // Reverting the space characterwordStart = i + 1; // Keeping a note of the position of the possible next word}i++;}(void)reverse(str + wordStart); // Reversing the last word in the given string
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).
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.
Quick Links
Legal Stuff