Skip to content

Instantly share code, notes, and snippets.

@mrjohannchang
Created October 25, 2012 02:36
Show Gist options
  • Save mrjohannchang/3950140 to your computer and use it in GitHub Desktop.
Save mrjohannchang/3950140 to your computer and use it in GitHub Desktop.
Reverse the order of words in a sentence.
#include <stdio.h>
#include <string.h>
void reverse_char_array(char * first, char * last) {
while (first != last && first != --last) {
*first ^= *last;
*last ^= *first;
*first++ ^= *last;
}
}
void reverse_string(char * sentence) {
reverse_char_array(sentence, &sentence[strlen(sentence)]);
}
void reverse_word(char * sentence) {
char * end_s = &sentence[strlen(sentence)], * end_w;
while (end_w != end_s) {
if (!(end_w = strchr(sentence, ' '))) end_w = end_s;
reverse_char_array(sentence, end_w);
sentence = end_w + 1;
}
}
int main(int argc, char ** argv) {
char sentence[] = "how are you";
reverse_string(sentence);
reverse_word(sentence);
printf("%s\n", sentence);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment