"Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank."
I'm assuming by this he means input something like...
We(blank)(blank)(blank)go(blank)to(blank)(blank)(blank)the(blank)mall!
... and output it like:
We(blank)go(blank)to(blank)the(blank)mall!
This is probably easier than I'm making it out to be, but still, I can't seem to figure it out. I don't really want the code... more so pseudo code.
Also, how should I be looking at this? I'm pretty sure whatever program I write is going to need at least one variable
, a while
loop, a couple if
statements, and will use both the getchar()
and putchar()
functions... but besides that I'm at a loss. I don't really have a programmers train of thought yet, so if you could give me some advice as to how I should be looking at "problems" in general that'd be awesome.
(And please don't bring up else
, I haven't got that far in the book so right now that's out of my scope.)
Many others have already used the last character logic in their code, but perhaps the following version is easier to read:
Like many other people, I am studying this book as well and found this question very interesting.
I have come up with a piece of code that only uses what has been explained before the exercice (as I am not consulting any other resource but just playing with the code).
There is a
while
loop to parse the text and oneif
to compare the current character to the previous one. Are there any edge cases where this code would not work ?Here is how I think of the algorithm of this exercise, in pseudo-code:
Example implementation in C:
I worked really hard at finding a solution that used only the material that has already been covered in the first part of the first chapter of the book. Here is my result:
I am at the same point in the book. and my solution goes with making a count++ if blank is found and making the count back to zero if anything other than blank is found.
For if statement I put another another check to check value of count (if zero) and then print.
Though at this point of learning I shouldn't be concern about efficiency of two methods but which one is efficient a.) Accepted solution here with while inside while or b.) the one I suggested above.
My code goes like below:
To do this using only while loops and if statements, the trick is to add a variable which remembers the previous character.
In C code: