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

31 lines
1.0 KiB
C

#include <stdio.h>
int detab(char s[],int lim, int col)
/*s is the string we need to replace, lim is the character limit
* and col is the size of a tab (8 characters usually so we use that)*/
{
int c, i; /*c is the character i0nteger representation and i is the column we are on*/
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n';)
if (c == '\t') {
int sp=col-i%col; /*Amount of spaces to replace the tab with*/
int st=i; /*Starting point*/
for (int co = 0; co<=sp && i < lim-1; co++ && i++) {
/*For each space we need to add, we increase the column count and add it
*to the array at position (starting point + spaces added so far)
* and we increase the spaces added so far*/
s[st+co] = ' ';
}
} else {
s[i] = c;
++i;
}
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*/
s[i+1] = '\0';
return i;
}