Implementation of the C Function strtrim()

Jul 1 · 4 min read

First, let’s take a look at the man page of this function. We can use the FreeBSD version of this function.

In other words, it will remove all the unnecessary white that you might have in a string, for instance:

Now that we know what it to do, let’s divide this implementation into small steps.

  1. Get the position within the string, where there is no white space at the beginning of it. In the case above, it would be index = 3, because str[3] == 'H'

2. Now let’s find the last valid position in the string.

str[15] == '!'

3. And then let’s copy this into a new array of character with the correct size, so we can have the length of the "Hello World!" string, without any white space at the beginning and or end of this string.

4. And now we can copy the correct characters to our trim string.

And now, we can create a new c file called trim.c and compile the strtrim() function implementation with a main() function.

Let’s test it out!

Resulting in the following output…

And so, we are done with our strtim() implementation. Hope this has been a good read to get you started on doing implementations of other functions!

Peace out.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade