/*------------------------------------------------------------------------------ * problem007.c: reverse a string **----------------------------------------------------------------------------*/ /* Copyright (c) 2009 Peter Bui. All Rights Reserved. * * Peter Bui * **------------------------------------------------------------------------------ * Includes **----------------------------------------------------------------------------*/ #include #include #include #include /*------------------------------------------------------------------------------ * Constants **----------------------------------------------------------------------------*/ #define MAX_STRLEN 1024 /*------------------------------------------------------------------------------ * Function Prototypes **----------------------------------------------------------------------------*/ static void reverse_words(char *); static void reverse_string(char *, char *); /*------------------------------------------------------------------------------ * Macros **----------------------------------------------------------------------------*/ #define swap(a, b) \ tmp = *(a); \ *(a) = *(b); \ *(b) = tmp; /*------------------------------------------------------------------------------ * Functions **----------------------------------------------------------------------------*/ static void reverse_words(char *s) { char *fp, *bp, *ep; char tmp; fp = s; bp = &s[strlen(s) - 1]; while (ispunct(*bp)) bp--; ep = bp + 1; reverse_string(fp, bp); fp = bp = s; while (bp < ep) { if (!isspace(*bp)) { fp = bp; if (ispunct(*fp)) { bp = bp - 1; while (isspace(*bp)) bp--; swap(fp, bp + 1); fp = bp = fp + 1; } while (!isspace(*bp) && bp < ep) bp++; reverse_string(fp, bp - 1); } bp++; } } static void reverse_string(char *front, char *back) { char *fp, *bp; char tmp; fp = front; bp = back; do { swap(fp, bp); } while (++fp < --bp); } /*------------------------------------------------------------------------------ * Main Execution **----------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { char buffer[MAX_STRLEN]; while (fgets(buffer, MAX_STRLEN, stdin)) { buffer[strlen(buffer) - 1 ] = 0; reverse_words(buffer); puts(buffer); } return (EXIT_SUCCESS); } /*------------------------------------------------------------------------------ * vim: sts=4 sw=4 ts=8 ft=c **----------------------------------------------------------------------------*/