Re: Comment on trim string function please



swengineer001@xxxxxxxxx wrote:
Just looking for a few eyes on this code other than my own.

void TrimCString(char *str)

Why not return a char *, like most other string functions?

char *TrimCString(char *str)

using char * enables you to piggyback your function in the
middle of other functions, eg
printf("%s\n", TrimCString(someString));

{
// Trim whitespace from beginning:
size_t i = 0;
size_t j;

while(isspace(str[i]))
{
i++;
}
if(i > 0)
{
for(j = 0; i < strlen(str); j++, i++)

move the strlen() outside the loop.
Maybe use memmove() instead of the loop.

{
str[j] = str[i];
}
str[j] = '\0';
}

// Trim whitespace from end:
i = strlen(str) - 1;

Use the strlen you computed before, when
you moved it out of the for loop above :)


while(isspace(str[i]))
{
i--;
}
if(i < (strlen(str) - 1))
{
str[i + 1] = '\0';

No need for the test.
when i >= (strlen(str) - 1) -- it can only be equal, anyway -- the
assignment overwrites a '\0' with a brand new '\0'.
Anyway, if you want to keep the test, use the computed strlen.

}
}


A couple what-if's

* what if a pass NULL to the function?
TrimCString(NULL);

* what if I pass a constant string literal to the function?
TrimCString(" 4 spaces at both ends ");
.



Relevant Pages