Exercise 1.18 - Remove trailing blanks and tabs


Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.


/* Write a Program to remove the trailing blanks and tabs from each input line
  and to delete entirely blank lines */

#define MAXLINE 1000

int mgetline(char line[],int lim);
int removetrail(char rline[]);

int main(void)
  int len;
  char line[MAXLINE];
    if(removetrail(line) > 0)

  return 0;

int mgetline(char s[],int lim)
  int i,c;

  for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
    s[i] = c;
  if( c == '\n')
  return i;

/* To remove Trailing Blanks,tabs. Go to End and proceed backwards removing */

int removetrail(char s[])
  int i;

  for(i=0; s[i]!='\n'; ++i)
  --i;  /* To consider raw line without \n */

  for(i >0; ((s[i] == ' ') || (s[i] =='\t'));--i)   
    ; /* Removing the Trailing Blanks and Tab Spaces */

  if( i >= 0) /* Non Empty Line */
    s[i] = '\n';
    s[i] = '\0';
  return i;

Run this


In the removetrail function, we go to the very end of the line and the trace back to the find the character which is not a space, tab and then replace it with 0. This eliminates the trailing blanks in a line. For the empty lines whose length is 0, we simply skip that from output and thus removing it.

Comments by Disqus