0
0
CProgramBeginner · 2 min read

C Program to Reverse Words in a String

You can reverse words in a string in C by splitting the string into words, then printing them in reverse order using a loop; for example, use strtok to split and store words, then print them backwards.
📋

Examples

Inputhello world
Outputworld hello
InputC programming is fun
Outputfun is programming C
Inputsingle
Outputsingle
🧠

How to Think About It

To reverse words in a string, first separate the string into individual words by detecting spaces. Then, store these words in a list or array. Finally, print the words starting from the last one to the first, joining them with spaces to form the reversed word order.
📐

Algorithm

1
Get the input string from the user.
2
Split the string into words using space as a delimiter.
3
Store each word in an array or list.
4
Print the stored words in reverse order separated by spaces.
5
End the output with a newline.
💻

Code

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

int main() {
    char str[100], *words[50];
    int count = 0;

    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    char *token = strtok(str, " ");
    while (token != NULL) {
        words[count++] = token;
        token = strtok(NULL, " ");
    }

    for (int i = count - 1; i >= 0; i--) {
        printf("%s", words[i]);
        if (i > 0) printf(" ");
    }
    printf("\n");

    return 0;
}
Output
world hello
🔍

Dry Run

Let's trace the input 'hello world' through the code.

1

Input string

str = 'hello world'

2

Split into words

words[0] = 'hello', words[1] = 'world', count = 2

3

Print words in reverse

Print 'world' then 'hello'

IterationWord StoredCount
1hello1
2world2
💡

Why This Works

Step 1: Splitting the string

The strtok function breaks the input string into words using space as a separator.

Step 2: Storing words

Each word pointer is saved in an array so we can access them later in reverse order.

Step 3: Reversing output

A loop prints the words starting from the last stored word to the first, reversing the word order.

🔄

Alternative Approaches

In-place reversal of entire string then each word
c
#include <stdio.h>
#include <string.h>

void reverse(char *start, char *end) {
    while (start < end) {
        char temp = *start;
        *start++ = *end;
        *end-- = temp;
    }
}

int main() {
    char str[100];
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    int len = strlen(str);
    reverse(str, str + len - 1);

    char *word_start = str;
    for (int i = 0; i <= len; i++) {
        if (str[i] == ' ' || str[i] == '\0') {
            reverse(word_start, str + i - 1);
            word_start = str + i + 1;
        }
    }

    printf("%s\n", str);
    return 0;
}
This method reverses the whole string first, then reverses each word to get the words in reverse order without extra storage.
Using stack to store words
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], stack[50][20];
    int top = -1;

    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    char *token = strtok(str, " ");
    while (token != NULL) {
        strcpy(stack[++top], token);
        token = strtok(NULL, " ");
    }

    while (top >= 0) {
        printf("%s", stack[top--]);
        if (top >= 0) printf(" ");
    }
    printf("\n");

    return 0;
}
This approach uses a stack (array) to store words, then pops and prints them in reverse order.

Complexity: O(n) time, O(n) space

Time Complexity

The program scans the string once to split words and once to print them in reverse, so it runs in linear time relative to the string length.

Space Complexity

It uses extra space to store pointers to words or copies of words, proportional to the number of words.

Which Approach is Fastest?

The in-place reversal method uses constant extra space and is faster in memory usage, but the strtok method is simpler and easier to understand.

ApproachTimeSpaceBest For
Using strtok and arrayO(n)O(n)Simplicity and clarity
In-place reversalO(n)O(1)Memory efficiency
Stack methodO(n)O(n)Explicit control over word storage
💡
Use strtok to split the string easily by spaces before reversing the words.
⚠️
Beginners often try to reverse the entire string without handling individual words, resulting in reversed letters but not reversed word order.