#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;
}
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
----- 01000111 01101111 00100000 01000011 00100000 00100001
And for the reverse it's just to look at the constructors to see:
Code:
std::string ret_str(str);
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
----- 01000111 01101111 00100000 01000011 00100000 00100001