1
1
/*
2
2
* Exercise 1-18. Write a program to remove trailing blanks and tabs from each
3
3
* line of input, and to delete entirely blank lines.
4
+ *
4
5
* By Faisal Saadatmand
5
6
*/
6
7
7
8
#include <stdio.h>
8
9
9
- #define MAXLINE 1000 /* maximum input line length */
10
- #define YES 1
11
- #define NO 0
10
+ #define MAXLINE 1000 /* maximum input line length */
12
11
13
12
/* functions */
14
- int getLine (char [], int );
15
- int delTrailingWS (char [], int );
16
- void delBlankLns (char [], int );
13
+ int getLine (char [], int );
14
+ int rightTrim (char [], int );
17
15
18
16
/* getLine function: read a line into s, return length */
19
17
int getLine (char s [], int lim )
@@ -33,59 +31,36 @@ int getLine(char s[], int lim)
33
31
return i ;
34
32
}
35
33
36
- /* delTrailingWS function: deletes trailing whitespaces and blank lines */
37
- int delTrailingWS (char s [], int len )
34
+ int rightTrim (char s [], int len )
38
35
{
39
- int i , blankLine ;
40
- int newLength = len ; /* new length of line after whitespaces removal */
36
+ int nw = 0 ;
41
37
42
- i = 0 ;
43
- blankLine = NO ;
44
-
45
- /* test for blanklines with witespaces */
46
- while (s [i ] == ' ' || s [i ] == '\t' || s [i ] == '\n' )
47
- ++ i ;
48
- if (i == len ) { /* remove whitespaces spaces form blank lines */
49
- s [0 ] = '\n' ;
50
- for (i = 1 ; s [i ] != '\0' ; ++ i )
51
- s [i ] = '\0' ;
52
- newLength -= i - 1 ;
53
- }
54
-
55
- if (s [0 ] == '\n' ) {
56
- blankLine = YES ;
38
+ if (s [-- len ] == '\n' ) {
39
+ s [len ] = '\0' ; /* remove newline character */
40
+ nw = 1 ; /* set flag */
57
41
}
58
42
59
- if (!blankLine ) { /* skip entirely blank lines */
60
- while (s [len ] == '\0' || s [len ] == '\n' ||
61
- s [len ] == ' ' || s [len ] == '\t' ) {
62
- s [len ] = '\0' ;
63
- -- len ;
64
- }
65
- s [len + 1 ] = '\n' ; /* insert newline char before null char */
66
- newLength = len + 2 ; /* plus 2 for the newline and null characters */
67
- }
68
- return newLength ;
69
- }
43
+ while (-- len >= 0 && (s [len ] == ' ' || s [len ] == '\t' ))
44
+ s [len ] = '\0' ;
45
+ ++ len ;
70
46
47
+ if (nw )
48
+ s [len ] = '\n' ; /* add back the newline character */
71
49
72
- /* delBlankLns function: deletes entirely blank lines */
73
- void delBlankLns (char s [], int len )
74
- {
75
- if (len == 1 && s [0 ] == '\n' )
76
- s [0 ] = '\0' ;
50
+ return ++ len ;
77
51
}
78
52
79
53
int main (void )
80
54
{
81
55
int len ; /* current line length */
82
- int newLen ; /* modified line length */
83
56
char line [MAXLINE ]; /* current input line */
84
57
85
58
while ((len = getLine (line , MAXLINE )) > 0 ) {
86
- newLen = delTrailingWS (line , len );
87
- delBlankLns (line , newLen );
59
+ len = rightTrim (line , len );
60
+ if (len == 1 && line [0 ] == '\n' ) /* delete if line is empty */
61
+ line [0 ] = '\0' ;
88
62
printf ("%s" , line );
89
63
}
64
+
90
65
return 0 ;
91
66
}
0 commit comments