Saturday, August 23, 2008

rtrim() in C

Another nifty php funktion that C and C++ miss is rtrim(). trim is a function, which removes whitespaces from the end of a string.
So here's my implementation of rtrim() for char arrays:


#include <string.h>

/**
\brief removes trailing whitespaces and tabs from a string.
\returns number of characters removed
*/
int trim(char *text)
{
int i;
int len;
int retval=0;
len=strlen(text);
for
(
i=len-1;
i>=0&&( text[i]==' ' || text[i]=='\t' );
i--
)
{
text[i]=(char)0;
retval++;
}
return retval;
}


It would not be too difficult to implement the possibility to trim other characters. Actually just an edition to 2 of the lines ;)

3 comments:

  1. wow i've never seen a for written like that before. anyways! thanks a lot!

    ReplyDelete
  2. IT IS RIDICULOUS ! THIS FUNCTION CAN BE WRITTEN ONLY IN 3 LINES

    ReplyDelete
  3. void rtrim(char *str,char trim_char=' ')
    {
    int n=strlen(str);
    while((n>0)&&(str[--n]==trim_char));
    str[n]='\0';
    }

    ReplyDelete