Last active
February 16, 2018 13:12
-
-
Save sqroot3/08aec67a18382416731c5ff41b3997e8 to your computer and use it in GitHub Desktop.
entab.c - Program that replaces a string of blanks by the min # of spaces & tabs required to generate identical output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define TABSIZE 8 | |
int main() | |
{ | |
int c, nchars, nspaces; | |
//nchars = number of chars, nspaces = number of spaces | |
nchars = nspaces = 0; | |
while((c = getchar()) != EOF) { | |
if(c == ' ') { | |
++nspaces; | |
} else { | |
//decide whether gap in between chars is long enough for a space | |
while(nspaces >= TABSIZE - nchars) { | |
putchar('\t'); | |
nspaces -= TABSIZE; | |
} | |
//insert all remaining spaces manually | |
while(nspaces > 0) { | |
putchar(' '); | |
--nspaces; | |
} | |
//at this point nspaces has to be 0, update nchars = 0 as well for correct "endpoint" evaluation | |
nchars = 0; | |
if(c != '\t') { | |
++nchars; | |
} | |
putchar(c); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Special thanks to CodeReview users who helped me improve the code.
https://codereview.stackexchange.com/questions/187639/entab-c-program-that-replaces-string-of-blanks-by-the-min-of-spaces-tabs-t