K&R C Exercise 1-23: Remove Comments from a C Program

Exercise 1-23. Write a program to remove all comments from a C program. Don’t forget to handle quoted strings and character constants properly. C comments don’t nest. Approach The core challenge is that the same character sequence means completely different things depending on context. A /* inside a string literal is not a comment. A …

K&R C Exercise 1-22: Fold Long Lines at Word Boundaries

Exercise 1-22. Write a program to “fold” long lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column. Line folding is the …

K&R C Exercise 1-21: entab — Replace Spaces with Tabs

Exercise 1-21. Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference? Approach entab is …

K&R C Exercise 1-20: detab — Replace Tabs with Spaces

Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter? Approach The key insight is that a tab does not …

K&R C Exercise 1-19: Reverse a String in C

Exercise 1-19. Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time. Approach The core algorithm is the classic two-pointer swap: place one index at the start of the string (i = 0) and one at the end (j = …

K&R C Exercise 1-18: Remove Trailing Blanks and Delete Blank Lines

Exercise 1-18. Write a program to remove trailing blanks and tabs from each line of input, and delete entirely blank lines. The challenge here is that you cannot know whether a blank or tab is “trailing” until you have seen everything that follows it on the same line. The solution splits the work into two …