Aug 22, 2016

K & R : Exercise 1.18 - Remove trailing space and tab

K & R : Exercise 1.18 - Remove trailing space and tab

Problem Statement

Exercise 1-18: Write a program to remove trailing blanks and tabs from each line of input and to delete entirely blank lines.


Solution

We need to find a pattern here, i.e white spaces (either tab or space) followed by \n. After finding the pattern it is to be be removed. Hence we need some kind of buffer to store space and tabs till we hit \n. Lets call it as buf, we cannot have it infinitely long lets limit it 1000 characters. We need to find till where the buf is filled. Lets use the variable idx to track it. Taking all the above input solution would look as follows.

#include <stdio.h>
#include <stdlib.h>
#define MAX_BUF_LEN 1000
int main()
{
  int buf[MAX_BUF_LEN] = {0,}; /* Holds temp white-space */
  int idx = 0; /* Indicates end index of buf */
  int ch;  /*Present input ch */
  int len; /* Present line length */


  while((ch = getchar()) != EOF) {
    if(ch == ' ' || ch == '\t') {
      /* Lets start storing it in buf */
      buf[idx] = ch;
      len++;
      idx++;
      if(idx >= MAX_BUF_LEN) {
         printf("ERROR: no buffer left\n");
         exit(0);
      }
    }else if (ch == '\n') {
      if(idx > 0) {
        /* There are some previous white-space */
        /* This condition is matching pattern which is to be removed */
        if(len != idx) {
          /* Line is not just filled with white space
             , hence retain the new line */
          putchar(ch);
        }
        idx = 0;
      }else if(idx == 0) {
        /* There were some non-white characters before*/
        putchar(ch);
      }
    }else {
      len++;
      if(idx > 0) {
        /* There white space characters before non-white space */
        /* Patter is matched here and lets dump all the white spaces here */
        int j = 0;
        for(j = 0; j < idx; j++){
          putchar(buf[j]);
        }
        putchar(ch);
        idx = 0;
      }else if(idx == 0) {
        /* Just put it back */
        putchar(ch);
      }
    }
  }
  return 0;
}

No comments :

Post a Comment