Search code examples
pythoncstringfgets

Mimic Python's strip() function in C


I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects.

Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.

fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.


Solution

  • There is no standard C implementation for a strip() or trim() function. That said, here's the one included in the Linux kernel:

    char *strstrip(char *s)
    {
            size_t size;
            char *end;
    
            size = strlen(s);
    
            if (!size)
                    return s;
    
            end = s + size - 1;
            while (end >= s && isspace(*end))
                    end--;
            *(end + 1) = '\0';
    
            while (*s && isspace(*s))
                    s++;
    
            return s;
    }