The first step is to understand the problem. As I read it over and over for several times at first I couldn't understand what exactly it wants me to do. It's because some concepts weren't clear or familiar to me before I searched for more information about tab. First, what is a tab and what is a tab stop exactly? A tab is a character represented by the escape sequence \t
in many contexts. Just like other characters such as letters or digits, it's a character, but with special usage, so it's not a wide space or 4 or 8 spaces as it appears to be. Being displayed like a wide space or 4 or 8 spaces is just what it's designed for, which aligns each tab-delimited group of texts on multiple lines to make the region look like a table, but underneath on the level the software sees it's just a character. Tab stops are positions on the line where the cursor goes when the Tab key is pressed. These positions are fixed on the line according to the width or number of characters (or columns, all referring to the same concept) with which the Tab character is displayed. For example, on Windows Notepad the default width for Tab is 8 characters, and when you type Tab key the cursor would move behind the 8th, 16th, 24th... character. You can type 0s on the first line to see the effect more clearly:
00000000000000000000000000000000
Ivan Hello World
This is a table
delimited by tab
Now reading the problem over again it's clear to me that it's about replacing the Tab characters with spaces while maintaining the original table look. Then you can start writing your code to calculate how many spaces are needed for each Tab. Here's my complete code for this exercise:
#include <stdio.h>
#define MAX_LENGTH 1000
#define LINE_NUM 100
#define TAB_WIDTH 8
int readLine(char line[], int maxLength);
void copy(char from[], char to[]);
void detab(char line[], char result[]);
main() {
printf("Input: \n");
char lines[LINE_NUM][MAX_LENGTH];
char line[MAX_LENGTH];
char result[MAX_LENGTH];
int lineId = 0, length = 0;
while ((length = readLine(line, MAX_LENGTH)) != 0) {
detab(line, result);
copy(result, lines[lineId]);
lineId++;
}
printf("Output: \n");
for (int i = 0; i <= lineId; i++) {
printf("%s\n", lines[i]);
}
}
int readLine(char line[], int maxLength) {
char ch;
int length = 0;
while ((ch = getchar()) != EOF && ch != '\n' && length < maxLength) {
line[length] = ch;
length++;
}
if (ch == '\n') {
line[length] = '\0';
}
return length;
}
void copy(char from[], char to[]) {
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
i++;
}
to[i] = '\0';
}
void detab(char line[], char result[]) {
int i = 0;
char ch;
int column = 0;
int spaces;
int nextTabStop;
while ((ch = line[i++]) != '\0') {
if (ch == '\t') {
spaces = TAB_WIDTH - column % TAB_WIDTH;
nextTabStop = column + spaces;
for (; column < nextTabStop; column++) {
result[column] = ' ';
}
} else {
result[column] = ch;
column++;
}
}
result[column] = '\0';
}