learningc/chapters/1/exercises/shared/functions/entab.c

38 lines
1.1 KiB
C

#include <stdio.h>
int entab(char s[], int lim, int col) {
int c, i, t;
for (i=0,t=0; i < lim-1 && (c=getchar())!=EOF && c!='\n';i++,t++) {
/*
* c is the character representation as integer
* i is the current column on the copied string
* t is the current column on the original string
*
* t is used to count tab stops because i goes back when spaces are replaced by tabs.
* i and t are both modified, however only i changes in contexts other than the routinal increase.
* c is set to i's position and t is only used in tab stop counting
*/
if (t >= col && t%col == 0 && s[i-1] == ' ' && s[i-2] == ' ') {
int x;
for (x = i; s[x-1] == ' ' && i-col < x; x--);
s[x] = '\t';
i = ++x;
}
s[i] = c;
}
if (c == '\n')
/*
* If it is the end of the string, represented by a new line,
* add that new line and increase it for the \0 addition
*/ {
s[i] = c;
}
/*Add the string end and return it to the previous context*/
if (lim-1 > i) {
s[i+1] = '\0';
} else {
s[lim-1] = '\0';
}
return i;
}