I need to expand tabs in an input line, so that they are spaces (with a width of 8 columns). I tried it with a previous code I had replacing the last space in every line greater than 10 characters with a ‘\n’ to make a new line. Is there an way in C to make tabs 8 spaces in order to expand them? I mean I am sure it is simple, I just can’t seem to get it.
Here’s my code:
int v = 0;
int w = 0;
int tab;
extern char line[];
while (v < length) {
if(line[v] == '\t')
tab = v;
if (w == MAXCHARS) {
// THIS IS WHERE I GET STUCK
line[tab] = ' ';
// set y to 0, so loop starts over
w = 0;
}
++v;
++w;
}
This isn’t really a question about the C language; it’s a question about finding the right algorithm — you could use that algorithm in any language.
Anyhow, you can’t do this at all without reallocating
line[]to point at a larger buffer (unless it’s a large fixed length, in which case you need to be worried about overflows); as you’re expanding the tabs, you need more memory to store the new, larger lines, so character replacement such as you’re trying to do simply won’t work.My suggestion: Rather than trying to operate in place (or trying to operate in memory, even) I would suggest writing this as a filter — reading from stdin and writing to stdout one character at a time; that way you don’t need to worry about memory allocation or deallocation or the changing length of line[].
If the context this code is being used in requires it to operate in memory, consider implementing an API similar to
realloc(), wherein you return a new pointer; if you don’t need to change the length of the string being handled you can simply keep the original region of memory, but if you do need to resize it, the option is available.