Subj : Re: Reverse words in a string (Another Interview question) To : comp.programming From : Randy Date : Tue Oct 04 2005 02:54 pm Roger Willcocks wrote: > "Randy" wrote in message > news:dhsgsb$dot$1@joe.rice.edu... .... > > That seems like a lot of work... it's hard to beat the canonical solution: > > #include > > void revtok(char* str, char sep) > { > char *tmp, *end; > do { > while (*str && *str == sep) str++; > end = str; > while (*end && *end != sep) end++; > tmp = str; str = end; > while (--end > tmp) { char t = *tmp; *tmp++ = *end; *end = t; } > } while (*str); > } > > void main(int argc, char* argv[]) > { > char str[] = "when in the course of human events"; > revtok(str, '\0'); > revtok(str, ' '); > printf("%s\n", str); > } > > -- > Roger That's a nice algorithm -- reverse the entire string then reverse each word back to right-way-round. Very clean. But it does introduce an interesting issue. Your code's two phase reversal of tokens -- the entire string then each word itself -- is counterintuitive. For the next person to understand what your code is doing, comments would be essential. Short of using a language that has builtins to do this, I definitely prefer your approach to manipulating each word. Very palindromic. Randy .