/* Reverse letters of the words, but not the words themselves */ /* Version 2: punctuation remains in place */ #include #define MAXWORD 40 /* Maximum word size */ enum flags { NO, YES, CAPS, UNDERCAST }; int wordchar(int c); int w_reverse(char s[], int len, int caps); int w_write(char s[], int len); int read_word(void) { int len; /* index/length of word[] */ int c; /* next character of input */ int w; /* flag: CAPS or UNDERCAST */ int caps; /* does the word start with Caps ? */ int all_caps; /* is the entire word CAPITAL ? */ char word[MAXWORD]; /* the word self */ len = 0; caps = all_caps = NO; while ((c = getchar()) != EOF) if ((w = wordchar(c))) { if (w == CAPS) { word[len++] = c; all_caps = YES; } else if (w == UNDERCAST) { word[len++] = c; if (all_caps == YES) { caps = YES; all_caps = NO; } } } else if (w == 0) { if (len) { w_reverse(word, len, caps); w_write(word, len); len = 0; caps = all_caps = NO; } putchar(c); } return c; } int w_reverse(char s[], int len, int caps) { int i, j; int swap; j = len -1; i = 0; if (caps == YES) { /* swap positions of caps */ s[i] = s[i] + 'a' - 'A'; /* convert a Capital to undercast */ s[j] = s[j] + 'A' - 'a'; /* convert a undercast to Capital */ } while (i < j) { swap = s[i]; s[i++] = s[j]; s[j--] = swap; } return 0; } int w_write(char s[], int len) { int i; for (i = 0; i < len; ++i) putchar(s[i]); return 0; } int wordchar(int c) { if (c >= 'A' && c <= 'Z') return CAPS; else if (c >= 'a' && c <= 'z') return UNDERCAST; else return 0; } int main(void) { while (read_word() > 0) ; return 0; }