How do I trim leading/trailing whitespace in a standard way?

后端 未结 30 2030
一个人的身影
一个人的身影 2020-11-22 02:06

Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I\'d roll my own, but I would think this is a common problem wit

30条回答
  •  無奈伤痛
    2020-11-22 02:36

    I'm only including code because the code posted so far seems suboptimal (and I don't have the rep to comment yet.)

    void inplace_trim(char* s)
    {
        int start, end = strlen(s);
        for (start = 0; isspace(s[start]); ++start) {}
        if (s[start]) {
            while (end > 0 && isspace(s[end-1]))
                --end;
            memmove(s, &s[start], end - start);
        }
        s[end - start] = '\0';
    }
    
    char* copy_trim(const char* s)
    {
        int start, end;
        for (start = 0; isspace(s[start]); ++start) {}
        for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}
        return strndup(s + start, end - start);
    }
    

    strndup() is a GNU extension. If you don't have it or something equivalent, roll your own. For example:

    r = strdup(s + start);
    r[end-start] = '\0';
    

提交回复
热议问题