trim the string 
Author Message
 trim the string

I have the function trim the string that get rid of the
white space from the beginning and the end of the string
below, but it didn't work could anyone tell me what's wrong
void trim(char *str)
{
??int len  strlen( str );
??int i;
??int n  -1;
??char *s;
??s  (char *)malloc(len+1);
??
??for( i0; i<len; i++ ){
??????if( str[i] ! '\n' && str[i] ! '\r' ){
??????????s[++n]  str[i];
??????}
??}
??s[++n]  '\0';
??strcpy(str, s);
??free(s);
Quote:
}



Tue, 11 Oct 2005 20:40:13 GMT  
 trim the string
Please don't post garbage to this newsgroup!

Dan

Quote:

>I have the function trim the string that get rid of the
>white space from the beginning and the end of the string
>below, but it didn't work could anyone tell me what's wrong
>void trim(char *str)
>{
>=a0=a0int len = strlen( str );
>=a0=a0int i;
>=a0=a0int n = -1;
>=a0=a0char *s;
>=a0=a0s = (char *)malloc(len+1);
>=a0=a0
>=a0=a0for( i=0; i<len; i++ ){
>=a0=a0=a0=a0=a0=a0if( str[i] != '\n' && str[i] != '\r' ){
>=a0=a0=a0=a0=a0=a0=a0=a0=a0=a0s[++n] = str[i];
>=a0=a0=a0=a0=a0=a0}
>=a0=a0}
>=a0=a0s[++n] = '\0';
>=a0=a0strcpy(str, s);
>=a0=a0free(s);
>}

--
Dan Pop
DESY Zeuthen, RZ group



Tue, 11 Oct 2005 22:23:08 GMT  
 trim the string

Quote:
>I have the function trim the string that get rid of the
>white space from the beginning and the end of the string
>below, but it didn't work could anyone tell me what's wrong

Well, what's wrong is that it doesn't trim all whitespace.  It also doesn't
discriminate between leading, trailing or embedded whitespace. :)

Quote:
>void trim(char *str)

I would advise returning a meaningful value from trim.  Perhaps a NULL
pointer if an error occurred, or a pointer to the trimmed string if not:

char *trim(char *str)

Quote:
>{
>??int len = strlen( str );
>??int i;
>??int n = -1;

This is confusing and misleading.  If n is an array index, its value should
always be bound between 0 and the length of the array-1.

I know that you had to do this because you preincrement 'n' below, but a
better way would have been to use the more appropriate type size_t and
postincrement your index:

        size_t i, n, len = strlen(str);

        /* ... */

        for (i = n = 0; i < len; i++)
        {
                if (str[i] != '\n' && str[i] != '\r' )          // WRONG ws test, btw
                        s[n++] = str[i];
        }

Note the comment on your whitespace test.  More on this later.

Quote:
>??char *s;
>??s = (char *)malloc(len+1);

Is there a declaration for malloc in scope?  Don't cast the return value of
malloc, and you should also test for the possibility of malloc failure:

        if ((s = malloc(len+1)) == NULL)
        {
                perror("trim");               // malloc failure--return NULL
                return NULL;            // Good reason for char *trim(), yes?
        }
??

Quote:
>??for( i=0; i<len; i++ ){
>??????if( str[i] != '\n' && str[i] != '\r' ){

What is whitespace?  Isn't it more than just the '\n' and '\r' characters?

Moreover, how are you addressing _leading_ and _trailing_ whitespace as per
your assignment?

You might want to look up the is* functions in your documentation (isalpha,
isdigit, isspace, etc).  These functions are all prototyped in ctype.h.

Good luck; hope this helps.

--
Robert B. Clark (email ROT13'ed)
Visit ClarkWehyr Enterprises On-Line at http://www.3clarks.com/ClarkWehyr/



Tue, 11 Oct 2005 23:04:24 GMT  
 trim the string

Quote:

> I have the function trim the string that get rid of the
> white space from the beginning and the end of the string
> below, but it didn't work could anyone tell me what's wrong

Hi,
I can not see in your code the check for a space (' '), and tab. And,
moreover you are removing '\n' and '\r' from every where and not from
the begining and end of the string only. I think you should do some
thing simililar to the code below:

============================
int isWS(char c) {
    if ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'))
        return 1;
    return 0;

Quote:
}

char* trim(char* str)  // your function ...
{
    int len = strlen( str );
    int s, e;
    char* str1;

    for( s=0; (s<len) && isWS(str[s]); s++);

    for( e=len-1; (e>=0) && isWS(str[e]); e--);

    str1 = (char *)malloc(e-s+2);

    strncpy(str1, (str+s), e-s+1);

    return str1;

Quote:
}

int main(int argc, char** argv) {
    char *newStr;
    if (argc < 2)
        return -1;
    printf ("STRING: '%s'\n", argv[1]);
    newStr = trim(argv[1]);
    printf ("After triming: '%s'\n", newStr);

    return 1;

Quote:
}

==========================================


Wed, 12 Oct 2005 03:43:21 GMT  
 trim the string

Quote:

> I have the function trim the string that get rid of the
> white space from the beginning and the end of the string
> below, but it didn't work could anyone tell me what's wrong
> void trim(char *str)
> {
>   int len = strlen( str );
>   int i;
>   int n = -1;
>   char *s;
>   s = (char *)malloc(len+1);

>   for( i=0; i<len; i++ ){
>       if( str[i] != '\n' && str[i] != '\r' ){
>           s[++n] = str[i];
>       }
>   }
>   s[++n] = '\0';
>   strcpy(str, s);
>   free(s);
> }

Try this (untested)

#include <string.h>

/* remove leading and trailing blanks in place, modifies *s */
char *trim(char *s)
{
   char *endptr;

   while (' ' == *s) s++;
   endptr = s + strlen(s);
   while ((endptr > s) && (' ' == *endptr)) *s-- = '\0';
   return s;

Quote:
} /* trim untested */

usage:

   char *s, *strimmed;
   ...
   strimmed = trim(s);

--

   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!



Wed, 12 Oct 2005 05:06:33 GMT  
 trim the string

Quote:

> I have the function trim the string that get rid of the
> white space from the beginning and the end of the string
> below, but it didn't work could anyone tell me what's wrong
> void trim(char *str)

======================
#include <stdio.h>
#include <malloc.h>

int isWS(char c) {  //can use isspace
    if ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'))
        return 1;
    return 0;

Quote:
}

char* trim(char* str)
{
    int len = strlen( str );
    int s, e;
    char* str1;

    for( s=0; (s<len) && isWS(str[s]); s++); //White spaces at the begining

    for( e=len-1; (e>=s) && isWS(str[e]); e--); //White spaces at the end

    if(0 != (str1=malloc(e-s+2))) {
        perror("Function trim");
        return 0;
    }
    strncpy(str1, (str+s), e-s+1);

    return str1;

Quote:
}

int main(int argc, char** argv) {
    char *newStr;
    if (argc < 2)
        return -1;
    printf ("STRING: '%s'\n", argv[1]);
    newStr = trim(argv[1]);
    if (!newStr)
        return -1;
    printf ("After triming: '%s'\n", newStr);

    return 1;

Quote:
}

======================================


Wed, 12 Oct 2005 08:15:52 GMT  
 trim the string

Quote:


>>I have the function trim the string that get rid of the
>>white space from the beginning and the end of the string
>>below, but it didn't work could anyone tell me what's wrong
> Try this (untested)

> #include <string.h>

> /* remove leading and trailing blanks in place, modifies *s */
> char *trim(char *s)
> {
>    char *endptr;

>    while (' ' == *s) s++;
>    endptr = s + strlen(s);
>    while ((endptr > s) && (' ' == *endptr)) *s-- = '\0';
>    return s;
> } /* trim untested */

Just looking at this I see flaws. The OP specified
"get rid of white space". This code only checks for the space
character. Also, a simple test would have shown that the function
does not work.

Althought the proposal, moving a pointer to the first character
that is not a space and return that pointer, may manage the problem,
I believe the better approach is to use function memmove.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

char *trim(char *s);
char *ctrim(const char *s);

int main(void)
{
    char *s, test[] = "   Hello World        \n";
    if(trim(test))
       printf("test = \"%s\"\n",test);
    if((s = ctrim("\n       Goodnight my dear         ")) != NULL)
       printf("s = \"%s\"\n",s);
    free(s);
    return 0;

Quote:
}

char *trim(char *s)
{
    char *s1;

    if(!s) return NULL;
    for(s1 = s;*s1 != '\0' && isspace((unsigned char)*s1); s1++) ;
    memmove(s,s1,strlen(s1)+1);
    for(s1 = s+strlen(s);s1 != s ; )
    {
       s1--;
       if(!isspace((unsigned char)*s1))
          break;
       *s1 = '\0';
    }
    return s;

Quote:
}

char *ctrim(const char *s)
{
    char *str;

    if(!s) return NULL;
    if((str = malloc(strlen(s)+1)) == NULL) return NULL;
    strcpy(str,s);
    if(trim(str) == NULL)
    {
       free(str);
       return NULL;
    }
    return str;

Quote:
}

----------
Al Bowers
Tampa, FL. USA

http://www.geocities.com/abowers822
comp.lang.c


Wed, 12 Oct 2005 19:02:40 GMT  
 trim the string
Another version that only scans the string ones ;) Not really pleased with
it but I think it does what it should. You could initialize last to str-1,
but then somenoe would say that it may cause problems. However, the if (!*s)
could be removed (by making the do-while loop into a while loop).

Cheers!

#include <stdio.h>

char *trim(char *str) {
  char *s, *dst, *last;

  s = dst = str;

  while (*s && isspace(*s)) s++;
  if (!*s) {*str = '\0'; return str; }

  do {
    if (!isspace(*s)) last = dst;
    *dst++ = *s++;
  } while (*s);

  *(last+1) = '\0';

  return str;

Quote:
}

int main() {
  char s1[] = " \t foo \t\n";
  char s2[] = " \t  \t\n";
  char s3[] = "foo";
  char s4[] = "foo \t\n";
  char s5[] = " \t foo";

  printf("'%s'\n", trim(s1));
  printf("'%s'\n", trim(s2));
  printf("'%s'\n", trim(s3));
  printf("'%s'\n", trim(s4));
  printf("'%s'\n", trim(s5));

  return 0;

Quote:
}



Wed, 12 Oct 2005 21:03:29 GMT  
 trim the string

Quote:



> >>I have the function trim the string that get rid of the
> >>white space from the beginning and the end of the string
> >>below, but it didn't work could anyone tell me what's wrong

> > Try this (untested)

> > #include <string.h>

> > /* remove leading and trailing blanks in place, modifies *s */
> > char *trim(char *s)
> > {
> >    char *endptr;

> >    while (' ' == *s) s++;
> >    endptr = s + strlen(s);
> >    while ((endptr > s) && (' ' == *endptr)) *s-- = '\0';
> >    return s;
> > } /* trim untested */

> Just looking at this I see flaws. The OP specified
> "get rid of white space". This code only checks for the space
> character. Also, a simple test would have shown that the
> function does not work.

That's why I marked it 'untested'. :-)  A simple revision does
work, below.  It you want to remove all white, rather than blanks,
simply replace "' ' == XXX" with "isspace(XXX)" and  #include
<ctype.h>.  Works for all modifiable strings.

#include <stdio.h>
#include <string.h>

/* remove leading and trailing blanks in place, modifies *s */
char *trim(char *s)
{
   char *endptr;

   while (' ' == *s) s++;
   endptr = s + strlen(s);
   while ((endptr > s) && (' ' == *(--endptr))) *endptr = '\0';
   return s;

Quote:
} /* trim */

int main(int argc, char **argv)
{
   while (--argc > 0) {
      printf("'%s'\n", argv[argc]);
      printf("'%s'\n\n", trim(argv[argc]));
   }
   return 0;

Quote:
}

c:\c\junk>.\a "  parm1 " "parm2 " "   parm3" "    "
'    '
''

'   parm3'
'parm3'

'parm2 '
'parm2'

'  parm1 '
'parm1'

--

   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!



Wed, 12 Oct 2005 22:51:25 GMT  
 trim the string

Quote:

> simply replace "' ' == XXX" with "isspace(XXX)" and  #include
> <ctype.h>.  Works for all modifiable strings.

isspace((unsigned char)XXX).  The ctype.h functions expect an
integer argument in the range of unsigned char, or EOF.

--
Hallvard



Wed, 12 Oct 2005 22:56:38 GMT  
 trim the string

Quote:

> I can not see in your code the check for a space (' '), and tab. And,
> moreover you are removing '\n' and '\r' from every where and not from
> the begining and end of the string only. I think you should do some
> thing simililar to the code below:

> ============================
> int isWS(char c) {
>     if ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'))
>         return 1;
>     return 0;
> }

Plus FF \f and (maybe? see recent flamewar) VT \v.
Or just use isspace from <ctype.h>, on as noted elsethread
an unsigned char value (cast).

Quote:
> char* trim(char* str)  // your function ...
> {
>     int len = strlen( str );
>     int s, e;

size_t is better; (signed) int is not guaranteed large enough
although on most (nearly all?) systems it is.

The parameter could be const char *, since you only read it.

Quote:
>     char* str1;

>     for( s=0; (s<len) && isWS(str[s]); s++);

>     for( e=len-1; (e>=0) && isWS(str[e]); e--);

A null loop body like that is often a bug; it's better to make clear
when you really mean it, such as { /* no-op */ } .  If you make
e size_t, as is best (above), you need to use the pre-test idiom:
  for( e=len; e && isWS(str[e-1]); --e ) { /*nop*/ }
  --e; /* or change usages below */
or take advantage of the fact that the last nonnull character
index in a string cannot exceed (size_t)-2:
  for( e = len-1; e != (size_t)-1 && isWS(str[e]); e-- ) { /*nop*/ }
/* cast not truly needed but avoids some silly warnings */

Quote:
>     str1 = (char *)malloc(e-s+2);

It's unnecessary and inadvised to cast the return from malloc in C
if it has been properly declared, usually by #include'ing <stdlib.h>,
as it must.  But you do need to check for failure (NULL).

Quote:
>     strncpy(str1, (str+s), e-s+1);

That never copies/writes a terminating null, since that maxlen
computation is never greater than the valid suffix length.  
As a result the returned 'string' is not valid.

Quote:
>     return str1;
> }

> int main(int argc, char** argv) {
>     char *newStr;
>     if (argc < 2)
>         return -1;
>     printf ("STRING: '%s'\n", argv[1]);
>     newStr = trim(argv[1]);
>     printf ("After triming: '%s'\n", newStr);

Since trim returned malloc'ed space, caller should
in general free() when done using it.

(And it's spelled 't{*filter*}'.  Or east of the pond, spelt.)

Quote:
>     return 1;

1 is not a particularly portable exit status, and even
where supported not sensible in this case.

Quote:
> }

- David.Thompson1 at worldnet.att.net


Tue, 18 Oct 2005 12:57:08 GMT  
 
 [ 11 post ] 

 Relevant Pages 

1. trimming a string

2. How to trim a string in a _variant_t

3. How to trim a String?

4. trim for strings

5. Is there any easier way to trim the string?

6. Trim a comma off end of string???

7. Help to trim spaces of a string

8. String.Trim() behavior

9. String.Trim is this correct functionality

10. String.Trim();

11. Need help to trim spaces off a string

12. Right trim string function in C

 

 
Powered by phpBB® Forum Software