Subj : Re: Reverse words in a string (Another Interview question) To : comp.programming From : Roger Willcocks Date : Wed Oct 05 2005 11:02 am "Willem" wrote in message news:slrndk5m0d.ege.willem@toad.stack.nl... > 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. Okay, how about: #include #include char* revstr(char* str, char* out) { char* end; while (*str == ' ') str++; end = str; while (*end && *end != ' ') end++; if (*end) { out = revstr(end, out); *out++ = ' '; } memcpy(out, str, end - str); *(out += end - str) = 0; return out; } void main(int argc, char* argv[]) { char out[100]; revstr("when in the course of human events", out); printf("%s\n", out); } -- Roger .