Jul 27, 2014

K&R Exercise 1.9 Replace multiple blank with single blank

Problem Statement

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.


I am assuming that blanks are represented by ' '. It can be easily extended to remove '\t' too.


  • First loop that takes character using getchar() till EOF.
  • Present variable that is got from getchar() is stored in c.
  • Since we need to remove continuous space, lets save the previous character in variable old_c.
  • When previous character is blank and present character is not a blank, then we will print using putchar both blank and present character.
  • If the present character is not blank then we will print it as usual.
  • End of the loop present character is assigned to old_c.
C implementation will look as follows-

#include <stdio.h>
int main()
   int c;  /* Present Charecter */
   int old_c; /* Previous Charecter */

   while((c = getchar()) != EOF) {
      if(old_c == ' ' && c != ' '){
         putchar(' ');
      }else if(c != ' '){
      old_c = c;
   return 0;

using the file redirection operation

$ cat text 
This is very    long             line.
$ ./e_1_09.out < text 
This is very long line.

No comments :

Post a Comment