I think you will find this task easier to code if you think of it in terms of the desired output. Build each output line by adding strings to it until you find one that does not belong. Print the current output line and start a new one. When there is nothing left to add, print the final line.