Home   Blog   Contact  |  Admin

How To: Trim Strings in C

Remove Last Character

Trim Characters From Start or End


Trimming characters off a string is a pretty fundamental task when dealing with strings. Most languages have fairly easy ways of doing this, but like many things, you need to know a few tricks to do it in C.

C Strings

What is a string in C? An array of characters right? No, there is a key difference, its an array of characters followed by a terminating null character '\0'. This null character signifies the end of the string.

Remove Last Character

To remove the last character, simply put a ternimating null where you want the string to finish.

#include <strings.h> ... char str[20] = "Hey there!"; str[strlen(str)-1] = '\0' printf("%s\n", str); // will print: Hey there

Function To Trim Characters Off End

#include <strings.h> void trim_from_end(char *str, int n){ str[strlen(str)-n] = '\0'; } int main(void){ char str[20] = "Hey there!"; trim_from_end(str, 3); printf("%s\n", str); return 0; }

The function trim_from_end removes n characters from the end of str. This program prints Hey The, as expected. So now you know, its pretty simple really.