Answer S8
/* Puzzle S08 -- trim */
#include <stdio.h>
#include <stdlib.h>
void trim( char *p )
{
/* Return immediately if empty string */
if ( !*p ) return;
/* Find the null at the end of the string */
char *end = p;
while ( *end ) end++ ;
/* Find the first non-white character, if any */
char *start = p;
while ( *p && isspace( *start ) ) start++ ;
/* Make the string empty if it is all whitespace */
if ( start==end )
{
*p = '\0';
return;
}
/* 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()
{
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;
}