/** * * Reverse the order of words in a string using minimal memory. * * This is an old an ancient technique so it's not exactly new or clever. * * Compile: cc -o reverse reverse.c * * Usage: ./reverse * or * ./reverse "Your phrase goes here" * * Copyright (c) 2001, Simon Wistow * * Released under the terms of the Gnu Public Licence * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * **/ #include #include #include void reverse(char* start, char* end); /* Reverse the order of words in a string */ int main (int argc, char ** argv) { /* The input */ char * string; /* Walk through the string */ char *p1, *p2; /* If we've been given an argument, then use that. Otherwise use the default. * we have to strdup it otherwise newer compilers automatically make it const * this could be fixed by using the -fwriteable-strings flag */ if (argc>1) { string = strdup(argv[1]); } else { string = strdup("The cow jumped over the moon"); } /* If there are no spaces then we don't need to do anything */ if(!strchr(string, ' ')) { goto PRINT; /* So, I like gotos ... sue me */ } /* First reverse the String in place using the old xor trick*/ reverse(string, string+strlen(string)-1); /* Now walk through the string and reverse strings in place */ for(p1=string; p1start; ++start, --end) { *start ^= *end; *end ^= *start; *start ^= *end; /* Or start ^= *end ^= *start ^= *end; */ } }