Last Updated: February 25, 2016
·
3.011K
· brendanjcaffrey

Reverse the Order of Words In a String (In C)

The easiest way to reverse the order of words in a string is pretty simple (once you wrap your head around it at least). Let's take a string of words like word1 word2 word3. The first step is to reverse the entire string, giving you 3drow 2drow 1drow. The next step is to reverse each word, one-by-one, back to its original order: word3 word2 word1.

Here's a quick implementation in C:

#include <stdio.h>
#include <string.h>

int word_length(char *str) {
 int i;
 for (i = 0; *str != ' ' && *str != '\0'; i++) str++;
 return i;
}

void switch_chars(char* one, char* two) {
 char temp = *one;
 *one = *two;
 *two = temp;
}

void substr_reverse(char *str, int len) {
 if (len < 2) return;
 char *i = str;
 char *j = str + len;

 for (; i < j; i++, j--) switch_chars(i, j);
}

void reverse_words(char *str) {
 substr_reverse(str, strlen(str) - 1);

 while (word_length(str) != 0) {
 substr_reverse(str, word_length(str) - 1);
 str += word_length(str) + 1;
 }
}

int main(int argc, char* argv[]) {
 char str[18] = "word1 word2 word3";
 reverse_words(str);

 printf("%s\n", str);
}