Q: Write a C program to reverse the order of words in a string. For simplicity, space has been chosen as word delimiter and punctuation is considered part of the word.
Example:
Input: Can you reverse the words in this string.
Output: string. this in words the reverse you Can
Time Complexity: O(log(n))
void reverse_word(char *word, int length)
{
int start;
int end = length - 1;
char temp;
for (start = 0; start < end; start++, end--) {
temp = word[start];
word[start] = word[end];
word[end] = temp;
}
}
void reverse_string(char *string)
{
int index;
int string_length = strlen(string);
int word_start_index = 0;
int word_length = 0;
// Reverse the original string
reverse_word(string, string_length);
for (index = 0; index < string_length; index++) {
// found word delimiter
if (string[index] == ' ') {
reverse_word(&string[word_start_index], word_length);
word_length = 0;
word_start_index = index + 1;
} else {
word_length++;
}
}
// Reverse the last word
if (word_length) {
reverse_word(&string[word_start_index], word_length);
}
}