Thread: How to eliminate extra whitespaces?

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    28

    How to eliminate extra whitespaces?

    How do I make many consecutive white spaces into one white space? I tried this:

    Code:
    	int c, last_c = '\0';
    	
    	while( (c=getchar()) != EOF ){
    		if( !isspace(c) && isspace(last_c) )
    			putchar(' ');
    		if( !isspace(c) ) 
    			putchar(c);
    		
    		last_c = c;
    	}
    which works, but is it the most efficient way to write it? Or is there at least a better way of doing this?
    Dat
    http://hoteden.com <-- not an porn site damnit!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but is it the most efficient way to write it?
    Most of the time it doesn't matter if your method is the most efficient, just make sure it's simple enough to understand and don't worry about performance unless there is a real bottleneck. Here is another way to do it:
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main ( void )
    {
      int ch;
    
      while ( ( ch = getchar() ) != EOF ) {
        if ( isspace ( ch ) ) {
          while ( isspace ( ch ) && ( ch = getchar() ) != EOF )
            ; /* Eat whitespace */
    
          putchar ( ' ' );
        }
    
        putchar ( ch );
      }
    
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. whitespaces
    By happyclown in forum C Programming
    Replies: 2
    Last Post: 01-06-2009, 10:33 PM
  2. buffer has extra contents in gtk+ 2.0
    By MK27 in forum Linux Programming
    Replies: 5
    Last Post: 08-04-2008, 11:57 AM
  3. sscanf & whitespaces
    By hannibar in forum C Programming
    Replies: 1
    Last Post: 05-10-2006, 09:06 AM
  4. From where these two extra bytes came?
    By Juganoo in forum C Programming
    Replies: 4
    Last Post: 12-24-2002, 05:32 PM
  5. Extracting Whitespaces
    By TechWins in forum C++ Programming
    Replies: 4
    Last Post: 04-18-2002, 07:28 PM