C Program to Reverse Words in a String
strtok to split and store words, then print them backwards.Examples
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the input 'hello world' through the code.
Input string
str = 'hello world'
Split into words
words[0] = 'hello', words[1] = 'world', count = 2
Print words in reverse
Print 'world' then 'hello'
| Iteration | Word Stored | Count |
|---|---|---|
| 1 | hello | 1 |
| 2 | world | 2 |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using strtok and array | O(n) | O(n) | Simplicity and clarity |
| In-place reversal | O(n) | O(1) | Memory efficiency |
| Stack method | O(n) | O(n) | Explicit control over word storage |
strtok to split the string easily by spaces before reversing the words.