#include<stdio.h>#include<string.h>#defineWHITESPACE_CHARS" \f\n\r\t\v"/*
Compile: cc -g -ansi -pedantic -Wall -O2 -o trim trim.c
Run: ./trim
*//* Prototypes. */char *trim(char *);
externchar *strdup();
intmain(intargc, char *argv[])
{
char *s = " hej hopp ";
printf("Trimmed: '%s'\n", trim(s));
printf("Not trimmed: '%s'\n", s);
return 0;
}
/* Create a copy of a NULL-terminated string. *//* Remove leading and trailing whitespace characters from the copy. *//* Return the copy. */char *
trim(char *string)
{
char *result = NULL, *ptr = NULL;
/* Ignore NULL pointers. */if (string)
{
ptr = string;
/* Skip leading whitespace. */while (strchr(WHITESPACE_CHARS, *ptr))
++ptr;
/* Make a copy of the remainder. */
result = strdup(ptr);
/* Move to the last character of the copy (that is, until the NULL char is reached). */for (ptr = result; *ptr; ptr++);
/* Move to the last non-whitespace character of the copy. */for (--ptr; strchr(WHITESPACE_CHARS, *ptr); --ptr);
/* Remove trailing whitespace. */
*(++ptr) = '\0';
}
return result;
}