ComtriS ComtriS - 1 month ago 13
C Question

Trim function in C, to trim in place (without returning the string)

char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);

int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}

if(*str == 0) {
return 0;
}

char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = 0;

return 0;
}

Answer
char testStr[] = "          trim this           ";
char* pTestStr = &testStr[0];
trim(&pTestStr);

void trim(char* str)
{
    if(!str)
        return;

    char* ptr = str;
    int len = strlen(ptr);

    while(len-1 > 0 && isspace(ptr[len-1]))
        ptr[--len] = 0;

    while(*ptr && isspace(*ptr))
        ++ptr, --len;

    memmove(str, ptr, len + 1);
}