Puzzle S8

Trim whitespace from the front and end of a string

[H-8]Write a function which removes whitespace characters from the beginning and end of a string. For example, the string

"   Spaces before, spaces after   " 

will be trimmed to

"Spaces before, spaces after" 

Whitespace in the middle of a string will not be removed. Use the isWhitespace() function from puzzle S02 or the standard isspace() function. Here is a testing function:

#include <stdio.h>
#include <stdlib.h>

void trim( char *p )
{
}

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 );
  }

  return 0;
}


Previous Page        Answer         Next Page         Home