-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrim-space.c
64 lines (52 loc) · 1.15 KB
/
trim-space.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* It trims trailing space or tab at the end of line or file.
*/
#include <ctype.h>
#include <stdio.h>
struct Token {
char ch;
long count;
};
int main(int argc, char *argv[]) {
int c;
int i;
int j;
int tokenIndex;
int numOfNewLine;
struct Token tokenList[100];
tokenIndex = 0;
numOfNewLine = 0;
while ((c = getchar()) != EOF) {
if (isspace(c)) {
if ('\n' == c) {
if (numOfNewLine <= 0)
putchar(c);
tokenIndex = 0;
numOfNewLine++;
} else {
if (tokenIndex <= 0 || tokenList[tokenIndex - 1].ch != c) {
tokenList[tokenIndex].ch = c;
tokenList[tokenIndex].count = 1;
tokenIndex++;
} else {
tokenList[tokenIndex - 1].count++;
}
}
} else {
while (numOfNewLine > 1) {
putchar('\n');
numOfNewLine--;
}
for (i = 0; i < tokenIndex; i++) {
for (j = 0; j < tokenList[i].count; j++) {
putchar(tokenList[i].ch);
}
}
tokenIndex = 0;
numOfNewLine = 0;
putchar(c);
}
}
return 0;
}