J
john_g83
have a bit of c code that is ment to take a string (that may or may not
have spaces before or after the string) i.e. " stuff ", and trims off
the whitespace before and after.
Code:
char *trim (char *str, char ch)
{
char *first, *last;
int count;
/* Move first to the first character that isn't the same as ch */
for (first = str; *first == ch; first++);
/* Move last to the null character. Thats the only way to know 100% we
are
* removing items from the end of the string */
for (last = first; *last != '\0'; last++);
/* Ok now we backtrack until we find a character that isn't the same as
ch */
for (last--; *last == ch; last--);
if ( first != str)
{
for (count=0; count< last - first + 1; count++)
str[count] = *(first+count);
str[count] = '\0';
}
else
{
str[last-first] = '\0';
}
return str;
}
the problem is that it always removes the last letter of str as well.
i.e.
" stuff " -> "stuf" any ideas why this is happening.
Cheers
John
have spaces before or after the string) i.e. " stuff ", and trims off
the whitespace before and after.
Code:
char *trim (char *str, char ch)
{
char *first, *last;
int count;
/* Move first to the first character that isn't the same as ch */
for (first = str; *first == ch; first++);
/* Move last to the null character. Thats the only way to know 100% we
are
* removing items from the end of the string */
for (last = first; *last != '\0'; last++);
/* Ok now we backtrack until we find a character that isn't the same as
ch */
for (last--; *last == ch; last--);
if ( first != str)
{
for (count=0; count< last - first + 1; count++)
str[count] = *(first+count);
str[count] = '\0';
}
else
{
str[last-first] = '\0';
}
return str;
}
the problem is that it always removes the last letter of str as well.
i.e.
" stuff " -> "stuf" any ideas why this is happening.
Cheers
John