Removing leading and trailing whitespace

This is a discussion on Removing leading and trailing whitespace within the C Programming forums, part of the General Programming Boards category; Hi; I want a way to remove leading and trailing whitespace from a string. I imagine i'm going to be ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    22

    Removing leading and trailing whitespace

    Hi;

    I want a way to remove leading and trailing whitespace from a string. I imagine i'm going to be making use of a loop and isspace(), but beyond this I cannot think how I can take in an array, trim the lead and trail to leave me with an array of just the middle bit.

    Does anyone have and ideas / pointers?

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    22
    Writing the post was an inspiration in itself for me

    Code:
    void striptrailspace( char *line )
    {
    
    	int i = strlen(line) - 1;
    
    	while ( i > 0 )
    	{
    		if ( isspace(line[i]) )
    		{
    			line[i] = '\0';
    		}
    		else
    		{
    			break;
    		}
    		i--;
    	}
    }

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Trimming trailing spaces is easy. Just find the first space at the end and replace it with '\0'. But be careful that you clear the right character without going out of bounds for something like an empty string or a string with nothing but spaces.

    Trimming leading spaces is harder. It's easiest if you can get away with just using a pointer into the array, then you can just do the inverse of the trailing technique and assign the first non-space character's address to a pointer.

    If you don't have that option, you need to actually shift the string:
    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>
    
    int main ( void )
    {
      char a[] = "   \t\v   \nThis is a test\n  \t \v    ";
      size_t walker = strlen ( a );
    
      printf ( "Before: |%s|\n\n", a );
    
      /* Trim trailing spaces */
      while ( walker > 0 && isspace ( a[walker - 1] ) )
        --walker;
    
      a[walker] = '\0';
    
      printf ( "Trailing: |%s|\n\n", a );
    
      /* Trim leading spaces */
      walker = strspn ( a, " \t\n\v" );
      memmove ( a, a + walker, strlen ( a + walker ) + 1 );
    
      printf ( "Leading: |%s|\n", a );
    
      return 0;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Removing Leading & Trailing Whitespace
    By EvilGuru in forum C Programming
    Replies: 11
    Last Post: 12-01-2005, 01:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21