Subj : Re: Reverse words in a string (Another Interview question) To : comp.programming From : Willem Date : Tue Oct 04 2005 08:29 pm Roger wrote: ) 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); ) } I'll give it a go: #include char *reverse(char *str) { char *ret, *src, *tgt; int len, wordlen; len = strlen(str); ret = malloc(len); src = str; tgt = ret + len; while (*src) { for (wordlen = 0; isspace(src[wordlen]); wordlen++) ; tgt -= wordlen + 1; tgt[0] = src[wordlen]; memcpy(tgt+1, src, wordlen); src += wordlen + 1; } return ret; } int main(int argc, char *argv[]) { if (argc < 2) return -1; return printf("%s\n", reverse(argv[1])); } Which is not the canonical solution, but it seems to me that it's a bit easier to understand what it does. It's probably a bit slower too, but that's because it's not inline. If the function is speced to return a copy, then it should be faster. SaSW, Willem -- Disclaimer: I am in no way responsible for any of the statements made in the above text. For all I know I might be drugged or something.. No I'm not paranoid. You all think I'm paranoid, don't you ! #EOT .