Skip to content

Instantly share code, notes, and snippets.

@iuridiniz
Last active July 15, 2025 08:21
Show Gist options
  • Select an option

  • Save iuridiniz/940b6093493b690fed3a78b90b5f122d to your computer and use it in GitHub Desktop.

Select an option

Save iuridiniz/940b6093493b690fed3a78b90b5f122d to your computer and use it in GitHub Desktop.
C strtrim function: Trims leading and trailing whitespace from a string in-place
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2025 Iuri Diniz <iuridiniz-at-EMAIL-BIG-G.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
#include <ctype.h>
#include <string.h>
/**
* @brief Trims leading and trailing whitespace from a string in-place.
*
* This function modifies the input string to remove any leading and trailing
* whitespace characters (as defined by isspace).
*
* @param str The character string to trim. The string must be modifiable.
* @return A pointer to the first non-whitespace character in the string.
*
* If the string is NULL, empty, or contains only whitespace, it returns
* a pointer to the beginning of the (now empty) string.
*/
static inline char *strtrim(char *str) {
char *start;
char *end;
// 1. Handle edge cases: If the string is NULL or already empty, do nothing.
if (!str || *str == '\0') {
return str;
}
// 2. Find the first non-whitespace character.
// The `start` pointer will be moved forward until it points to a
// character that is not a space.
start = str;
while (isspace((unsigned char)*start)) {
start++;
}
// 3. Handle strings that contain ONLY whitespace.
// If `start` now points to the end of the string ('\0'), it means
// the entire string was whitespace. We make the original string empty.
if (*start == '\0') {
*str = '\0';
return str;
}
// 4. Find the last non-whitespace character.
// The `end` pointer starts at the end of the string and moves
// backward until it finds a non-whitespace character.
end = str + strlen(str) - 1;
while (end > start && isspace((unsigned char)*end)) {
end--;
}
// 5. Add the null terminator.
// Place the null terminator right after the last non-whitespace character
// to officially end the string there.
*(end + 1) = '\0';
// 6. Return the new start of the string.
return start;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment