Leading and Trailing Blanks 
Author Message
 Leading and Trailing Blanks

Hello -
        I am wondering if anyone out there has a program (or knows of one)
that allows one to strip leading and trailing blanks from a string.
ex:

        char test[20];
        strcpy(test,"  TESTING  ");
        printf("%s", test);

will produce an output like
  TESTING  

that has blanks at the beginning of "TESTING". I would like to
have the following result

TESTING

that has no leading blanks.

I would *greatly* appreciate any type of help or hints in working with
this.

I'll be looking out here, but e-mails are also appreciated :)

TIA

Casey



Mon, 22 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

:       I am wondering if anyone out there has a program (or knows of one)
: that allows one to strip leading and trailing blanks from a string.
: ex:
:
:       char test[20];
:       strcpy(test,"  TESTING  ");
:       printf("%s", test);

How about this:

        char test[20], temp[20];
        strcpy(test,"  TESTING  ");
        sscanf(test, "%s", temp);
        printf("%s", temp);

--
Huayong

WWW home pages:                           Email:



Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:

>Hello -
>    I am wondering if anyone out there has a program (or knows of one)
>that allows one to strip leading and trailing blanks from a string.
>ex:
>    char test[20];
>    strcpy(test,"  TESTING  ");
>    printf("%s", test);
>will produce an output like
>  TESTING  
>that has blanks at the beginning of "TESTING". I would like to
>have the following result
>TESTING
>that has no leading blanks.
>I would *greatly* appreciate any type of help or hints in working with
>this.

Try something like this:

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

       char test[BIG_ENOUGH], *beg, *end;

       beg = "    TESTING     ";

       /* Skip leading white space characters */

       while(isspace(*beg))
          ++beg;

       strcpy(test, beg);

       /* Remove trailing blanks */

       end = strrchr(test, '\0');
       if (end > test)
       {
          --end;
          while(isspace(*end))
             --end;
          end[1] = '\0';
       }

Kurt
--
| Kurt Watzka                             Phone : +49-89-2180-6254




Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

:
: Hello -
:       I am wondering if anyone out there has a program (or knows of one)
: that allows one to strip leading and trailing blanks from a string.
: ex:
:
:       char test[20];
:       strcpy(test,"  TESTING  ");
:       printf("%s", test);
:
: will produce an output like
:   TESTING  
:

  Check out Snipets 10/95 at Simtel \msdos\c\snip1095.zip.  You will will
100s of C programming functions and tips, incuding deadling with trailing
and leading blanks.



Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks


Quote:

>Hello -
>    I am wondering if anyone out there has a program (or knows of one)
>that allows one to strip leading and trailing blanks from a string.
>ex:

>    char test[20];
>    strcpy(test,"  TESTING  ");
>    printf("%s", test);

>will produce an output like
>  TESTING  

>that has blanks at the beginning of "TESTING". I would like to
>have the following result

>TESTING

>that has no leading blanks.

This might work:

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

char * tstr = "  TESTING  ";
char * strip (char * dest, char * src);

int main (void) {

  char result[256];

  strip(result, tstr);
  printf("tstr=%s.\t length = %d\n", tstr, strlen(tstr));
  printf("result=%s.\t length = %d\n", result, strlen(result));
  return 0;

Quote:
}
}

char * strip (char * dest, char * src) {

  char * fptr, * bptr;  /* front and back ptrs */

  if (NULL == src || '\0' == *src) {
    *dest = '\0';
    return src;
  }
  fptr = src;
  bptr = src + strlen(src) - 1;
  while(' ' == *fptr && '\0' != *fptr) ++fptr;
  while(' ' == *bptr && bptr > src) --bptr;
  if (bptr >= fptr) {
    int len = 1 + (bptr-fptr);
    strncpy(dest, fptr, len);
    *(dest + len) = '\0';
  }
  else
    *dest = '\0';
  return dest;

Quote:
}
}

/* end */

It was tested with null and zero-length strings.  Also, a string with

all spaces succeeded. You could probably substitute "isspace(*ptr)" for

the ' ' condition in the while loops - this will take care of tabs, etc.

Hope you like it, it's all I got.

Psychovoid 2007

        "Just because it's bad doesn't mean it won't be popular. After
        all, it's Microsoft."     ___
                            __   (.x.)   __



Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:

> Hello -
>         I am wondering if anyone out there has a program (or knows of one)
> that allows one to strip leading and trailing blanks from a string.
> ex:

>         char test[20];
>         strcpy(test,"  TESTING  ");
>         printf("%s", test);

> will produce an output like
>   TESTING

> that has blanks at the beginning of "TESTING". I would like to
> have the following result

> TESTING

The following code has not been tested, so probably contains typos.
It should serve to illustrate the algorithm.

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

#define TRUE 1
#define FALSE 0

char *dupstr( str );    /* defined below */

/**************************************************************/
/* trimstr - Remove leading and trailing blanks from a string */
/*           Return TRUE (OK) or FALSE (Error)                */
/**************************************************************/
int trimstr( char *str )
{
{
        char *buff, *start, *end;
        int *len;

        /* MAKE A COPY OF THE STRING */
        buff = dupstr( str );
        if (buff==NULL) return( FALSE );

        /* FIND FIRST NON-BLANK CHAR */
        start = buff;
        while (start==' ') start++;

        /* TRIM TRAILING BLANKS */
        len = strlen( start );
        end = start+len-1;
        while (end>=start && *end==' ') *(end--)='\0';

        /* COPY BACK TO ORIGINAL STRING */
        strcpy( str, start );

        /* FREE TEMP BUFFER */
        free( buff );

        return( TRUE );

Quote:
}
}

/*******************************************************************/
/* dupstr - Emulate non-ANSI strdup() function: duplicate a string */
/*******************************************************************/
char *dupstr( char *str )
{
{
        char *newstr = malloc( strlen(str)+1 );

        if (newstr) strcpy( newstr, str );
        return( newstr );

Quote:
}
}

--
#####################################################################

                      Emmenjay Consulting
    Sofware Development          System Administration/Management
    Applications Support              PC Installation/Maintenance
    Training                                    Technical Writing
    Windows/Unix               General Consulting/Troubleshooting

PO Box 909                                             Ph 018 240 704
Kensington 2033
AUSTRALIA    
#####################################################################



Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:

> Hello -
>         I am wondering if anyone out there has a program (or knows of one)
> that allows one to strip leading and trailing blanks from a string.
> ex:

Here's the way I do it.  This is a bit verbose, but I was going for
clarity, not conciseness.  Use it along the lines of:

   char   test[ 10 ];

   strcpy( test, "  test  " );
   lrtrim( test );

[Replaced //foo\n with /*foo */\n in entire document, for C content. -mod]

   /* test now contains "test" */

/* Function:     void lrtrim() */
/* */
/* Description:  remove leading and trailing blanks from a        */
/*               string, in place all leading and trailing        */
/*               whitespace is removed                            */
/* */
/* Parameters:   char *st - string to trim */
/* */
void lrtrim( char *st )
{
{
  /* pointer to last non-space char seen */
  /* */
  char     *lastNonBlank = st - 1;

  /* pointer to left-trimmed string */
  /* */
  char     *newString;

  /* pointer to original string */
  /* */
  char     *oldString;              

  /*  initially, assume we're starting at the beginning */
  /* */
  newString = oldString = st;

  /*  skip leading blanks to find the new starting char */
  /* */
  while (isspace( *oldString ))
    ++oldString;

  /*  now copy all characters, starting from the first non-blank,  */
  /*  to the beginning of the string.  e.g., if the string was "  */
  /*  test", then newString would be pointing at the first 't',   */
  /*  while oldString would be pointing at the first space        */
  /*                                                              */
  /*  additionally, always keep track of the location (in the new  */
  /*  string) of the last non-space character seen.  initially,   */
  /*  this is set to one char before the beginning of the string, */
  /*  since we haven't seen any yet                               */
  /* */
  while (*oldString != '\0')
  {
    if (! isspace( *oldString ))          /* non-space? */
      lastNonBlank = newString;           /* note it */

    *newString++ = *oldString++;          /* move the char */
  }

  /*  the last non-blank should be our last character.  put a 0   */
  /*  terminator *after* it.  if we never saw a non-blank, this   */
  /*  puts the term at the first position of the string -- just   */
  /*  what we want                                                */
  /* */
  lastNonBlank[ 1 ] = '\0';

  return;

Quote:
}
}

-paul


Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

: Hello -
:       I am wondering if anyone out there has a program (or knows of one)
: that allows one to strip leading and trailing blanks from a string.
: ex:

:       char test[20];
:       strcpy(test,"  TESTING  ");
:       printf("%s", test);

: will produce an output like
:   TESTING  

: that has blanks at the beginning of "TESTING". I would like to
: have the following result

: TESTING

: that has no leading blanks.

: I would *greatly* appreciate any type of help or hints in working with
: this.

: I'll be looking out here, but e-mails are also appreciated :)

Even though this has nothing at all to do with C language, if you have
the source (I assume that you do,) check out regex find and replace of
your editor.

Even if you don't have the source, you might be able to use emacs to
interactively regex edit the binary.

If your editor does not do regex magic, perl has been ported to a vast
majority of platforms (cf. comp.lang.perl.)

Hope this helps,

/Alby



Tue, 23 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

I have some comments on a number of the articles in this thread so I've
put them all in this post.

 >
 > Hello -
 >         I am wondering if anyone out there has a program (or knows of one)
 > that allows one to strip leading and trailing blanks from a string.
 > ex:
 >
 >         char test[20];
 >         strcpy(test,"  TESTING  ");
 >         printf("%s", test);
 >
 > will produce an output like
 >   TESTING  
 >
 > that has blanks at the beginning of "TESTING". I would like to
 > have the following result
 >
 > TESTING
 >
 > that has no leading blanks.

And, I presume no training blanks. Also do you just want to strip spaces
or white-space (tabs etc.) in general?

...



...

Quote:
>       /* Remove trailing blanks */

>       end = strrchr(test, '\0');

Curious (but correct) use of strrchr. strchr() would have the same effect
here since a string terminates on the first uccurrence of '\0'. It might be
more typical to write:

        end = test + strlen(test);

While not particularly relevant in this case strlen has a better chance of
being well optimised than strchr or strrchr.

...



...

Quote:
>The following code has not been tested, so probably contains typos.
>It should serve to illustrate the algorithm.

Always test code before posting if you can. It takes little effort and
can save time later on.

Quote:
>        /* MAKE A COPY OF THE STRING */
>        buff = dupstr( str );

This seems a little heavyweight for a simple operation. If, say, the
standard library string handling functions started using malloc (which
can be slow) on every call I wouldn't be happy with the implementation.

Quote:
>        if (buff==NULL) return( FALSE );

Also it creates a result code which is otherwise unnecessary.

Quote:

>        /* FIND FIRST NON-BLANK CHAR */
>        start = buff;
>        while (start==' ') start++;

>        /* TRIM TRAILING BLANKS */
>        len = strlen( start );
>        end = start+len-1;

If the original string has zero length this will evaluate to buff-1 which
is illegal if buff points to the start of an array.

Quote:
>        while (end>=start && *end==' ') *(end--)='\0';

It's only necessary to zero the first trailing blank.

Quote:

>        /* COPY BACK TO ORIGINAL STRING */
>        strcpy( str, start );

Since you're modifying the original string it is probably better to do the
whole operation in place hence not requiring the temporary malloc'd buffer.

...

...

Quote:
>  while (*oldString != '\0')
>  {
>    if (! isspace( *oldString ))          /* non-space? */
>      lastNonBlank = newString;           /* note it */

>    *newString++ = *oldString++;          /* move the char */
>  }

If there are no leading blanks (i.e. newString == oldString) this does a lot
of unnecessary (but harmless) copying.

...



...

Quote:
>How about this:

>        char test[20], temp[20];
>        strcpy(test,"  TESTING  ");
>        sscanf(test, "%s", temp);
>        printf("%s", temp);

This won't work if there is whitespace in the string. That's not the
case in this particular example but I assume there will be in general.

...



...

Quote:



>>Hello -
>>       I am wondering if anyone out there has a program (or knows of one)
>>that allows one to strip leading and trailing blanks from a string.
>>ex:

>>       char test[20];
>>       strcpy(test,"  TESTING  ");
>>       printf("%s", test);

>>will produce an output like
>>  TESTING  

>>that has blanks at the beginning of "TESTING". I would like to
>>have the following result

>>TESTING

>>that has no leading blanks.

>This might work:

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

>char * tstr = "  TESTING  ";
>char * strip (char * dest, char * src);

>int main (void) {

>  char result[256];

>  strip(result, tstr);
>  printf("tstr=%s.\t length = %d\n", tstr, strlen(tstr));

                                     (int) ^
Quote:
>  printf("result=%s.\t length = %d\n", result, strlen(result));

                                         (int) ^

The return type of strlen is size_t. This is an unsigned integer but is
otherwise unspecified, therefore you need to cast it as an argument to
printf. int is probably OK here, although unsigned long is correct
in general.

...

Quote:
>char * strip (char * dest, char * src) {

>  char * fptr, * bptr;  /* front and back ptrs */

>  if (NULL == src || '\0' == *src) {
>    *dest = '\0';
>    return src;
>  }

It would be more consistent to return dest here.

Quote:
>  fptr = src;
>  bptr = src + strlen(src) - 1;
>  while(' ' == *fptr && '\0' != *fptr) ++fptr;

if *fptr is a space you've already determined that it isn't a null character.

Quote:
>  while(' ' == *bptr && bptr > src) --bptr;
>  if (bptr >= fptr) {
>    int len = 1 + (bptr-fptr);
>    strncpy(dest, fptr, len);

There's a lot of unnecessary (for the instance) baggage in strncpy, it is
generally better to use memcpy where it will do the job. In this case you
also have the opportunity to use memmove and support src and dest pointing
to the same array.

...



...

Quote:
>Even though this has nothing at all to do with C language, if you have
>the source (I assume that you do,) check out regex find and replace of
>your editor.

I suspect the idea is an algorithm that will output any string stripped
of leading or trailing spaces, including ones generated during program
execution or read from files. If you can solve this with regex in your
editor perhaps you could explain a little more! :-)

Quote:
>Even if you don't have the source, you might be able to use emacs to
>interactively regex edit the binary.

Don't even think about applying regex to binaries.

-------------------------------------------------------------------------------

Anyway here's a program that demonstrates a slightly different approach:

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

int main(void)

{
{
    char *ptr;
    int  len;
    char test[20];

    strcpy(test,"  TESTING  ");

    for (ptr = test; *ptr == ' '; ptr++)  /* Or use isspace() */
        ;

    if ((len = strlen(ptr)) != 0)
        while (ptr[len-1] == ' ')         /* Or use isspace() */
            len--;
    }

    printf("%.*s", len, ptr);
    return 0;

Quote:
}
}

--
-----------------------------------------


-----------------------------------------


Wed, 24 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Here's a function which will strip leading and trailing blanks:

static char *strip(char *str)
    {
    char           *cp;

    while( *str == ' ' )
        ++str;

    for( cp = str; *cp; cp++ )
        {
        if( *cp == ' ' )
            {
            *cp = '\0';
            break;
            }
        }

    return(str);
    }

Note that "   TESTING ABC  "
will become "TESTING"

Embedded blanks are not allowed.

-Jerzy
--
===============================================================================

#include <std_disclaimer.h>
===============================================================================



Wed, 24 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:

>    I am wondering if anyone out there has a program (or knows of one)
>that allows one to strip leading and trailing blanks from a string.

Was this assigned as a homework problem?  Or are you trying to learn C on
your own?  In the latter case, in order to learn something, you should
at least try to write some code yourself, and then show us what you have
written, and then we could give you hints as to what you have done wrong.  

                      - Kevin Jay Miller
 `



Wed, 24 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:

>Here's a function which will strip leading and trailing blanks:

[ ... ]

Quote:
>Note that "   TESTING ABC  "
>will become "TESTING"
>Embedded blanks are not allowed.

If this behavior is desired, it can be reduced to one line:

        string = strtok(string, " ");
        string = strtok(string, " ");
    Later,
    Later,
    Jerry.
    Jerry.

/* I can barely express my own opinions; I certainly can't
 * express anybody else's.
 * express anybody else's.
 *
 *
 * The universe is a figment of its own imagination.
 * The universe is a figment of its own imagination.
 */
 */



Thu, 25 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:


>>Here's a function which will strip leading and trailing blanks:
>[ ... ]
>>Note that "   TESTING ABC  "
>>will become "TESTING"
>>Embedded blanks are not allowed.
>If this behavior is desired, it can be reduced to one line:
>    string = strtok(string, " ");

Hardly.  After strtok is done with the input buffer, the first element in
the buffer will be the leading blank string (possibly 0-length) terminated
by a NULL. The desired text will be after the second token.

-Jerzy



Fri, 26 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks


Quote:

>>If this behavior is desired, it can be reduced to one line:

>>       string = strtok(string, " ");

>Hardly.  After strtok is done with the input buffer, the first element in
>the buffer will be the leading blank string (possibly 0-length) terminated
>by a NULL. The desired text will be after the second token.

No, Jerry is right. What you describe may be desirable behaviour for
strtok but it is not what it actually does. That is:

1. it skips over *all* leading separator characters. If it hits a null
   character strtok returns a null pointer

2. it notes the position of the start of token then scans until it finds
   a separator character (or a null character).

3. If it didn't encounter a null character in 2. it sets the separator
   character position to null to terminate the token and moves the pointer
   one position on.

4. It notes the current position internally for use by a subsequent call
   and returns a pointer to the token string.

5. Subsequent calls to strtok cause the sequence of operations above to
   start from the saved position if their first argument is a null pointer.

As a result of this strtok never returns a pointer to a zero length
string - it either returns a pointer to the next non-zero length token
or a null pointer if there are no more.

--
-----------------------------------------


-----------------------------------------



Sat, 27 Jun 1998 03:00:00 GMT  
 Leading and Trailing Blanks

Quote:



>>>Here's a function which will strip leading and trailing blanks:
>>[ ... ]
>>>Note that "   TESTING ABC  "
>>>will become "TESTING"
>>>Embedded blanks are not allowed.
>>If this behavior is desired, it can be reduced to one line:
>>        string = strtok(string, " ");
>Hardly.  After strtok is done with the input buffer, the first element in
>the buffer will be the leading blank string (possibly 0-length) terminated
>by a NULL. The desired text will be after the second token.

A properly functioning strtok will _never_ return a string of 0 length
or a string which includes _any_ delimiter character, not to mention a
string composed entirely of delimiters.  

If the strtok you're using now ever does either of these, I'd suggest
pulling out your handy copy of the standard, reading up on how it's
supposed to work, and writing a new one that works correctly.  (or you
could go find the BSD code for it, but strtok is simple enough that
looking very hard isn't likely worth the effort.)
    Later,
    Jerry.

/* I can barely express my own opinions; I certainly can't
 * express anybody else's.
 *
 * The universe is a figment of its own imagination.
 */



Mon, 29 Jun 1998 03:00:00 GMT  
 
 [ 17 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Leading and Trailing Blanks

2. Help with RegEx - checking for leading chars with trailing numbers

3. Newbie: remove leading/trailing space

4. removing trailing and leading spaces

5. COleVariant class object strips off any leading/trailing zeros

6. Removing leading/trailing spaces

7. COleVariant class object strips off any leading/trailing zeros

8. truncating leading/trailing zeros with CString::Format();

9. COleVariant class object strips off any leading/trailing zeros

10. Search string where sub_string has trailing blanks

11. Compare string and skip trailing blanks

12. formatted integer io, no leading blanks?

 

 
Powered by phpBB® Forum Software