Truncate Well That String

Nothing can be more disconcerting than text lopped off before the end of the li

This truncating issue was more of a problem back in the old text mode days. Monitors (terminals), had a fixed column width. The standard width was usually 80 columns, or 80 characters of text (including spaces) on a line. Even so, good programmers could confirm the terminal’s column width, which might also be 40 or 64 characters.

Regardless of where the far right column loomed, good programming practice involved formatting text so that it fit neatly within that column width limit. Inelegant programs simply continued their text, slicing words in half and other ugliness. Elegant programmers wrapped their words, ending a line of text at a word boundary. Humans appreciate such efforts.

Your task this month is to write a program that properly truncates a string of text. The truncation must happen at a word boundary, also known as a white space character: a space, tab, or newline.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char *truncate(char *text, int width);

int main()
{   
    char sample[] = "Please lop me off at a word boundary, not in the middle of a word.";
    int trunc;

    trunc = 40;

    printf("Truncated at column %d:\n",trunc);
    puts(truncate(sample,trunc));

    return(0);
}   

char *truncate(char *text, int width)
{   
}

Using the skeleton provided above as your starting point, craft the truncate() function. Note that the truncating width is presented as a variable, trunc. Also — major hint — the string.h and chtype.h header files are included, although your code isn’t obligated to use either one.

As I admonish every month, please try this exercise on your own before peeking at my solution, linked to below. The C language offers many solutions to the same problem, no one of which is more correct than the other, although ways exist, both elegant and clumsy, to solve any programming puzzle.

Exercise Solution

Leave a Reply