Difficulty: ★ ★ ★ ☆
As you might already know, the C language lacks plenty o’ functions readily available in other programming languages. Many of these functions, or “methods,” deal with strings. Though C includes a few basic string functions in its library, the C Lords have determined that when you need another such function, you must code it yourself.
The topic for this month’s Exercise is to craft a trim() function, which is one of those capabilities present in other programming languages but not directly in C. What this function does is to remove whitespace characters from both ends of a string.
As a reminder, whitespace characters include space, newline, and tab. The POSIX standard also adds form-feed (\f), carriage return (\r), and vertical tab (\v).
Below is a code skeleton to help get you started. This code runs, but it’s missing the trim() function and the statements to call the function and output the trimmed strings.
2026_04_01-Lesson.c
#include <stdio.h> /* put the trim() function here */ int main() { char *sample[] = { " one ", "\ttwo\n", "", " ", "a", " x ", NULL, " \t three \n", "four", " five", "six ", " seven eight " }; int size,x; /* obtain array size */ size = sizeof(sample)/sizeof(sample[0]); /* output trimmed strings */ for( x=0; x<size; x++ ) { /* output string and trimmed string */ } return 0; }
The skeleton includes an array sample[] that contains a slew of sample strings to trim. The strings represent a variety of possibilities such as an empty string, a string with only spaces, and NULL. These items are included because your trim() function solution must account for everything!
You can see that I don’t prototype the trim() function, so its behavior is truly at your discretion.
Here is sample output from my solution:
' one ' => 'one' ' two ' => 'two' '' => '' ' ' => '' 'a' => 'a' ' x ' => 'x' '(null)' => Bad string ' three ' => 'three' 'four' => 'four' ' five' => 'five' 'six ' => 'six' ' seven eight ' => 'seven eight'
I can think of multiple ways to code a trim() function, but don’t overthink things! As a suggestion, I recommend tackling the problem one step at a time.
Please try this exercise on your own before you peek at my solution, which I’ll post in a week.