Is this in C ?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str_trim, str[] = " the string with leading and trailing spaces ";
int i, j, stop=0, length=strlen(str);
/* create space for the copying */
str_trim = (char*) malloc(length*sizeof(char));
if(!str_trim)
{
printf("Error not enough heap space\n");
return -1;
}
/* remove all leading whitespaces */
for(i=0, j=0; str[i]; ++i)
if(!stop && (str[i] == ' ' || str[i] == '\t'))
; /* skip it */
else
{/* copy everything after the leading spaces */
stop=1;
str_trim[j++] = str[i];
}
str_trim[j] = '\0';
/* remove any tailing whitespace */
length=strlen(str_trim) -1;
for(;str_trim[length] == ' ' || str_trim[length] == '\t'; length--)
; /* just skoot on down there */
/* eliminate any further whitespaces */
str_trim[length +1] = '\0';
printf("Results:\n");
printf("\tOrrig string: \"%s\"\n", str);
printf("\tTrim string: \"%s\"\n", str_trim);
free(str_trim);
return 0;
}