Mimic Python's strip() function in C

后端 未结 4 1269
旧时难觅i
旧时难觅i 2021-01-12 22:29

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

4条回答
  •  轮回少年
    2021-01-12 23:21

    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;
    }
    

提交回复
热议问题