Re: Comment on trim string function please
- From: badc0de4@xxxxxxxxx
- Date: Thu, 10 Jul 2008 10:39:22 -0700 (PDT)
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 ");
.
- Follow-Ups:
- Re: Comment on trim string function please
- From: swengineer001@xxxxxxxxx
- Re: Comment on trim string function please
- References:
- Comment on trim string function please
- From: swengineer001@xxxxxxxxx
- Comment on trim string function please
- Prev by Date: Re: Comment on trim string function please
- Next by Date: Re: Comment on trim string function please
- Previous by thread: Re: Comment on trim string function please
- Next by thread: Re: Comment on trim string function please
- Index(es):
Relevant Pages
|