Skip to content

Instantly share code, notes, and snippets.

@ozars
Last active October 18, 2018 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozars/132d95a1302c0a646a0b42de0a00d4d2 to your computer and use it in GitHub Desktop.
Save ozars/132d95a1302c0a646a0b42de0a00d4d2 to your computer and use it in GitHub Desktop.
A useful trim function in C for non-NULL terminated strings

I was looking for a qucik trim function for non-null terminated strings in C. I came up with below solution which worked for me:

#include <ctype.h>  /* for isspace */
#include <stddef.h> /* for size_t  */

int memtrim(const char *mem, size_t size, const char **begin, const char **end)
{
    const char *temp_begin;
    const char *temp_end;
    if (begin == NULL) {
        begin = &temp_begin;
    }
    if (end == NULL) {
        end = &temp_end;
    }
    *begin = mem;
    *end   = mem + size;
    for(; *end > *begin && isspace((unsigned char)*(*end-1)); (*end)--);
    for(; *begin < *end && isspace((unsigned char)**begin); (*begin)++);

    return *end == *begin;
}

What it does (in that order):

  • Trim from right, store it to the end if provided.
  • Trim from left, store it to the begin if provided.
  • Return true if all characters are whitespace.

Usage:

  • Providing the chunk mem as NULL is undefined behavior.
  • If you need both left and right trim, provide both begin and end.
  • If you need just right trim, provide just end (pass begin as NULL).
  • If you need just left trim, provide just begin (pass end as NULL). However, you need to check return value as well to see if the chunk consists of all whitespace characters, because in this case begin will not be modified. This behavior can be easily reversed by changing order of for loops.
  • Address of the chunk itself mem can be provided as begin. This may be useful if you are working on a pointer that you don't own, therefore don't care about its address to free later.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment