How to reverse words in a sentence using Python and C
This is a technical problem I attempted recently. The problem was to reverse the words in a sentence. For example, The quick brown fox jumped over the lazy dog. becomes dog. lazy the over jumped fox brown quick The. I had to solve the problem first using Python, and then using C. In addition, the C version could only use 1 extra character of memory. I solved the Python version easily, but the C version was too difficult for me. Here are possible solutions.
Python version
sentence = "The quick brown fox jumped over the lazy dog."
words = sentence.split()
sentence_rev = " ".join(reversed(words))
print sentence_rev
C version
Credit for this solution goes to Hai Vu
#include <stdio.h>
/* function declarations */
void reverse_words(char *sentence);
void reverse_chars(char *left, char *right);
/* main program */
int main()
{
char mysentence[] = "The quick brown fox jumped over the lazy dog.";
reverse_words(mysentence);
printf("%s\n", mysentence);
return 0;
}
/* reverse the words in a sentence */
void reverse_words(char *sentence)
{
char *start = sentence;
char *end = sentence;
/* find the end of the sentence */
while (*end != '\0') {
++end;
}
--end;
/* reverse the characters in the sentence */
reverse_chars(start, end);
/* reverse the characters in each word */
while (*start != '\0') {
/* move start pointer to the beginning of the next word */
for (; *start != '\0' && *start == ' '; start++) ;
/* move end pointer to the end of the next word */
for (end=start; *end != '\0' && *end != ' '; end++) ;
--end;
/* reverse the characters in the word */
reverse_chars(start, end);
/* move to next word */
start = ++end;
}
}
/* reverse the characters in a string */
void reverse_chars(char *left, char *right)
{
char temp;
while( left < right) {
temp = *left;
*left = *right;
*right = temp;
++left;
--right;
}
}