/* Puzzle S08 -- trim */ #include <stdio.h> #include <stdlib.h> void trim( char *p ) { /* Find the first non-white character */ char *start = p; while ( isspace( *start ) ) start++ ; /* Find the null at the end of the string */ char *end = p; while ( *end ) end++ ; /* Find the last non-white character */ while ( isspace( *--end ) ) ; /* Put a null after the last non-white character */ *++end = '\0' ; /* Move characters down to the front of the buffer */ while ( *p++ = *start++ ) ; } int main(int argc, char *argv[]) { char buffer[ 100 ]; char *trials[] = { " The game is afoot! ", "The game is afoot!", " The game is afoot!", "The game is afoot! ", "\n\nNewLines and tabs count as Whitespace\n\n\t\t", "\n\tInternal\ttabs\t \tShould Remain \t", "", "Empty strings should pass right through", " \t\n\t ", "Strings of all whitespace should be reduced to empty" }; int j ; for ( j=0; j<sizeof(trials)/sizeof(char *); j++ ) { strcpy( buffer, trials[j] ); trim( buffer ); printf("-->%s<--\n", buffer ); } system("PAUSE"); return 0; }
Comments: