Created
October 25, 2012 02:36
-
-
Save mrjohannchang/3950140 to your computer and use it in GitHub Desktop.
Reverse the order of words in a sentence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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