Problem Statement
Exercise 1-9: Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.Solution
I am assuming that blanks are represented by ' '. It can be easily extended to remove '\t' too.Strategy
- First loop that takes character using getchar() till EOF.
- Present variable that is got from getchar() is stored in c.
- Since we need to remove continuous space, lets save the previous character in variable old_c.
- When previous character is blank and present character is not a blank, then we will print using putchar both blank and present character.
- If the present character is not blank then we will print it as usual.
- End of the loop present character is assigned to old_c.
#include <stdio.h> int main() { int c; /* Present Charecter */ int old_c; /* Previous Charecter */ while((c = getchar()) != EOF) { if(old_c == ' ' && c != ' '){ putchar(' '); putchar(c); }else if(c != ' '){ putchar(c); } old_c = c; } return 0; }
Output
using the file redirection operation
$ cat text This is very long line. $ ./e_1_09.out < text This is very long line.
Links
Next Article - K&R Exercise 1.10 Making tabs and backspaces visible in unambiguous wayPrevious Article - K&R Exercise 1.8 Write a program to count blanks, tabs and newlines
All Article - K & R Answers
No comments :
Post a Comment