Aug 30, 2016

K & R : Exercise 1.21 - Replace space with minimum tab - entab

K & R : Exercise 1.21 - Replace space with minimum tab - entab

Problem

Write a program entab that replaces strings of blank by minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or single blank would suffice to reach a tab stop which should be given preference.


Solution

We are converting only spaces into tabs and spaces. Lets assume that we convert 4 space into 1 tab. So if there are 6 spaces it will get converted into 1 tab and 2 spaces. Hence we need to count how many spaces are there. We can take decision of conversion only when we hit a non white characters. Converting above ideas into C Program.

#include <stdio.h>

#define SPACE_TO_TAB 4

int main()
{
  int space_count = 0, i;
  int ch;

  while((ch = getchar()) !=EOF) {
    if(ch == ' ') {
      space_count++;
    }else {
      if(space_count > 0) {
        for(i = 0; i< space_count/SPACE_TO_TAB; i++) {
          putchar('\t');
        }
        for(i = 0; i< space_count % SPACE_TO_TAB; i++) {
          putchar(' ');
        }
        space_count = 0;
      }
      putchar(ch);
    }
  }
  return 0;
}

Links

No comments :

Post a Comment