Re: Comment on trim string function please
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 10 Jul 2008 17:32:50 GMT
swengineer001@xxxxxxxxx <swengineer001@xxxxxxxxx> wrote:
Just looking for a few eyes on this code other than my own.
void TrimCString(char *str)
{
// Trim whitespace from beginning:
I guess I would trim from the end first since then you have less
copying to do afterwards.
size_t i = 0;
size_t j;
while(isspace(str[i]))
isspace() expects an int and not a char as it's argument.
{
i++;
}
if(i > 0)
{
for(j = 0; i < strlen(str); j++, i++)
{
str[j] = str[i];
}
str[j] = '\0';
}
An alternative would be to use memmove() here, so you don't
have to do it byte by byte. Also callling strlen() each time
through the loop is a bit of a waste of time - it doesn't
change and can be replaced by a check if str[i] is '\0'.
// Trim whitespace from end:
i = strlen(str) - 1;
Careful: This could set 'i' to -1 (if the string consistet of white
space only) and then the rest won't work anymore.
while(isspace(str[i]))
{
i--;
}
if(i < (strlen(str) - 1))
{
str[i + 1] = '\0';
}
}
Here's an alternative version using pointers (and trying to
minimize the number of calls of strlen()):
void
TrimCString( char *str )
{
char *p,
*q;
/* Check that we've got something that looks like a string */
if ( ! str || ! * str )
return;
/* Trim from end */
for ( p = str + strlen( str ) - 1; p != str && isspace( ( int ) *p ); p-- )
/* empty */ ;
if ( p == str ) /* only white space in string */
{
*str = '\0';
return;
}
*++p = '\0';
/* Trim from start */
for ( q = str; isspace( ( int ) *q ); q++ )
/* empty */ ;
if ( q != str )
memmove( str, q, p - q + 1 );
}
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- Follow-Ups:
- Re: Comment on trim string function please
- From: Bill Reid
- 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: inline assembly
- Next by Date: Re: Comment on trim string function please
- Previous by thread: Comment on trim string function please
- Next by thread: Re: Comment on trim string function please
- Index(es):
Relevant Pages
|