Here's a solution to reverse the words in a string while keeping the characters within each word in their original order:
#include <stdio.h>
#include <string.h>
void reverseRange(char* str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
void reverseWords(char* str) {
int len = strlen(str);
// First reverse the entire string
reverseRange(str, 0, len - 1);
// Then reverse each word
int start = 0;
for (int i = 0; i <= len; i++) {
if (str[i] == ' ' || str[i] == '\0') {
reverseRange(str, start, i - 1);
start = i + 1;
}
}
}
int main() {
char str[] = "Hello World from C";
printf("Original: %s\n", str);
reverseWords(str);
printf("Reversed: %s\n", str);
return 0;
}
This solution works in two steps:
- Reverse the entire string
- Reverse each word individually
For example:
Original string: "Hello World from C"
After full reverse: "C morf dlroW olleH"
After word reverse: "C from World Hello"
Time complexity: O(n) where n is the length of the string
Space complexity: O(1) as we're doing it in-place
Alternative solution using a temporary buffer (if in-place modification isn't required):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* reverseWords(const char* str) {
int len = strlen(str);
char* result = (char*)malloc(len + 1);
// Copy string to result
strcpy(result, str);
// Count words
int wordCount = 1;
for (int i = 0; str[i]; i++) {
if (str[i] == ' ') {
wordCount++;
}
}
// Create array of word positions
char** words = (char**)malloc(wordCount * sizeof(char*));
int wordIndex = 0;
words[wordIndex++] = result;
for (int i = 0; result[i]; i++) {
if (result[i] == ' ') {
result[i] = '\0';
words[wordIndex++] = &result[i + 1];
}
}
// Create final result
char* final = (char*)malloc(len + 1);
int pos = 0;
// Copy words in reverse order
for (int i = wordCount - 1; i >= 0; i--) {
strcpy(&final[pos], words[i]);
pos += strlen(words[i]);
if (i > 0) {
final[pos++] = ' ';
}
}
final[pos] = '\0';
free(words);
free(result);
return final;
}
int main() {
const char* str = "Hello World from C";
printf("Original: %s\n", str);
char* reversed = reverseWords(str);
printf("Reversed: %s\n", reversed);
free(reversed);
return 0;
}
This second solution:
- Creates a new string instead of modifying the original
- Uses extra space but might be more suitable if the input string is const or immutable
- Has O(n) time complexity but O(n) space complexity
- Is more complex but potentially more flexible for different use cases
Both solutions handle:
- Multiple spaces between words
- Leading/trailing spaces (if present)
- Single word inputs
- Empty strings
Choose the first solution if you:
- Need to minimize space usage
- Can modify the input string
- Want simpler code
Choose the second solution if you:
- Can't modify the input string
- Need to preserve the original string
- Don't mind the extra space usage