Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.09 on page 20

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.



Solution by Dabeau

#include <stdio.h>

main()
{
	char c;
	char prev_c; /* previous character */

	prev_c = 0;
	while ((c = getchar()) != EOF)
	/* output c if it's not a blank OR if the previous c is not a blank */
		if (c != ' ' || prev_c != ' ') { 
			putchar(c);
			prev_c = c;
		}
}

Solution by Richard Heathfield

#include <stdio.h>

int main(void)
{
  int c;
  int inspace;

  inspace = 0;
  while((c = getchar()) != EOF)
  {
    if(c == ' ')
    {
      if(inspace == 0)
      {
        inspace = 1;
        putchar(c);
      }
    }

    /* We haven't met 'else' yet, so we have to be a little clumsy */
    if(c != ' ')
    {
      inspace = 0;
      putchar(c);
    }
  }

  return 0;
}

Solution by Chris Sidi

instead of having an "inspace" boolean, you can keep track of the previous character and see if both the current character and previous character are spaces:

#include <stdio.h>

/* count lines in input */
int
main()
{
        int c, pc; /* c = character, pc = previous character */

        /* set pc to a value that wouldn't match any character, in case
        this program is ever modified to get rid of multiples of other
        characters */

        pc = EOF;

        while ((c = getchar()) != EOF) {
                if (c == ' ')
                        if (pc != ' ')   /* or if (pc != c) */ 
                                putchar(c);

                /* We haven't met 'else' yet, so we have to be a little clumsy */
                if (c != ' ')
                        putchar(c);
                pc = c;
        }

        return 0;
}


Solution by Stig Brautaset

I am hiding behind the fact that break is mentioned in the introduction!

#include <stdio.h>

int main(void)
{
	int c;
	while ((c = getchar()) != EOF) {
		 if (c == ' ') {
			putchar(c);
		 	while((c = getchar()) == ' ' && c != EOF)
				;
		}
		if (c == EOF)
			break; /* the break keyword is mentioned
				* in the introduction... 
				* */

		putchar(c);
	}
	return 0;
}

Solution by Anthony Walters

Here's another solution from Anthony, nut after posting it, I noticed that it looks suspiciously like Stig's solution above!

#include <stdio.h>

main()
{
  int inputchar;

  while((inputchar = getchar()) != EOF)
    {
      if(inputchar == ' ')
	{
	  putchar(inputchar);
	  while((inputchar = getchar()) == ' ')
	    { /* do nothing */ }
	}
      if(inputchar != EOF)
	putchar(inputchar);
    }
}

Solution by OneSadCow

Here is another solution, which is slightly more compact than any of the solutions presented here.

#include <stdio.h>

main(){
    int c, d;
    d = EOF;
    while ((c = getchar()) != EOF){
        if (!((d == ' ') && (c == ' ')))
            putchar(c);
        d = c;
    }
}

Solution by Platwna

Here is my solution (enjoy!):

#include <stdio.h>

void main()
{
        int c;
        int kena;
        kena = 0;
        while ((c = getchar()) != EOF)
        {
                if (c == ' ')
                {
                        ++kena;
                        if (kena < 2)
                        {
                                putchar(c);
                        }
                }
                if (c != ' ')
                {
                        kena = 0;
                        putchar(c);
                }
        }
}

Solution by pezcore

This is my solution. It was designed not to use logical operators or breaks statements, as they have not been introduced in K&R before example 1.9. Also, it only uses one variable and does not require the use of a "last char" or place holder variable . The main loop executes as follows: read a single char from input and immediately put it to output, regardless of what it is. Then, if that char was a space, continue to read more chars (thus removing them from the input buffer) until it is not a space, and put that char on the output too.

#include <stdio.h>

main(){
    char c;

    while((c = getchar()) != EOF){
        putchar(c);
        if (c == 0x20){
            while ((c=getchar()) == 0x20);
            putchar(c);
        }
    }
}


Solution by Indianlamp

Here is my solution: The first "if" condition checks and prints the character if it's not a space, the second "if" condition prints the first space, after that, if the "while loop" encounters a space, it keeps advancing the to next character, the third "if" condition prints the non-space character advanced to in the second "while loop".

#include<stdio.h>

int main()
{
	int c;
	
	while((c = getchar()) != EOF)
	{
		
		if (c != ' '){
			putchar(c);
		
		} 
				if (c == ' '){
				putchar(c);
				while (c == ' '){
					c = getchar();
					
					if (c != ' '){
						putchar(c);
						}
					}
			}
	}
	
	return 0;
}

Solution by Amarakala

Try this

int main(int argc, char** argv) {
    int c;
    int prevchar;
    
     while((c = getchar()) != EOF)
    {
        if(c != prevchar || prevchar != ' ')
            putchar(c);            
        prevchar = c;
    }
    
}

Solution by Lvictor

And here is another solution:

#include <stdio.h>

int main(){
  int c;

  while((c = getchar()) != EOF){
    if(c  == ' '){
      while((c = getchar()) == ' ')
        ;
      putchar(' ');
    }
    putchar(c);
  }
}

Solution by Vijaykartha

Here's another solution:

#include <stdio.h>

int main()
{
   int c;
   while ((c=getchar())!=EOF) //This keeps getting characters and checking if it is End of File
   {
     putchar(c);              //This outputs each character and if it is a blank, outputs it once
     if (c == ' ')            //If the character is a blank, then it goes into a while loop till the next non-blank character
      {
        while (c == ' ')      //This while loop keeps getting characters and checks if the next character is still blank
        c=getchar();         //This is part of while loop that keeps getting blank characters without outputting it.
        putchar(c);         //This is outside of the while loop and if a non-blank character is encountered, it is outputted because the outer while loop will get the next character. So, we don't want to missout on a non-blank character.
      }
   }
}

Solution by Ada123

This is another bad approach from me:

#include <stdio.h>

int main() {
    int c, s = 0;         
    
    while ( (c = getchar() ) != EOF ) {
        if (c == ' ') {
            ++s;
        }
            
        if(c == ' ') {
            while (s > 1) {
                printf("\b");
                s--;
            }    
        }
        else {
            printf("%c ", c);
        }
    }
    
}

Solution by sl4y3r 0wn3r

/*
Exercise 1-9. Write a program to copy its input to its output, replacing each
string of one or more blanks by a single blank.
*/
#include <stdio.h>
int main(void)
{
  int c = EOF;

  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\t') {
      while ((c = getchar()) == ' ' || c == '\t')
        ;
      putchar(' ');
    }
    putchar(c);
  }

  return 0;
}

Solution by User:_Kessinger

#include<stdio.h>

void main(){
    int c,blank=0;
    while((c = getchar()) != EOF){ // Input character
        if(c != ' '){ // if char not blank
            putchar(c); // output char
            blank = 0; // reset blank count
        }
        if(c==' ' && blank<1){ // if char is blank
            putchar(c); // output blank (only allowed once)
            blank++;    // increment blank
        }
        if(c == '\n')  // reset blank on newline
            blank = 0;
    }
}

Solution by Vastousen

Another quick solution

#include <stdio.h>


int main() {
	
	int c;
	
	c=getchar();
	while(c != EOF) {
		printf("%c", c);
		while (c == ' ') {
			c=getchar();
			if (c != ' ') {
				printf("%c", c);
			}
		}
		c=getchar();
	} 
}
		

Solution by Mark Lam

Quick update to the first solution by me - adding a line to show the extra spaces actually removed:

#include <stdio.h>

int main(void)
{
    int c;
    int ns;
    
    ns = 0;

    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            if (ns == 0)
            {
                ns = 1;
                putchar(c);
            }
        }
        if (c != ' ')
        {
            ns = 0;
            putchar(c);
        }
    }
    printf("%d\n", c);
    return 0;
}

Solution by Dave

My version:

include <stdio.h>

int main()
{
        char c;
        int blanks;
        while( (( c=getchar())!=EOF)  && !(blanks==2) )
        {
                if(c == ' ')
                {
                blanks++;
                printf("\nBlank detected, amount of blanks: %d\n", blanks);
                }
                else
                {
                putchar(c);
                }
        }
        return 0;
}

Solution by guzmalalo

Only IF and !=

#include <stdio.h>
#define SPACE ' '

int main ()
{
    int c;
    int nb = 0; 
    while((c = getchar()) != EOF){

        //if (c == SPACE) // (optional), you can assume c is already a blank and increment nb
        ++nb;
	
        if (c != SPACE)
            nb = 0;

        if(nb < 2)
            putchar(c);
    }
    return 0;
}
Personal tools