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

后端 未结 30 2374
一个人的身影
一个人的身影 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:37

    I know there have many answers, but I post my answer here to see if my solution is good enough.

    // Trims leading whitespace chars in left `str`, then copy at almost `n - 1` chars
    // into the `out` buffer in which copying might stop when the first '\0' occurs, 
    // and finally append '\0' to the position of the last non-trailing whitespace char.
    // Reture the length the trimed string which '\0' is not count in like strlen().
    size_t trim(char *out, size_t n, const char *str)
    {
        // do nothing
        if(n == 0) return 0;    
    
        // ptr stop at the first non-leading space char
        while(isspace(*str)) str++;    
    
        if(*str == '\0') {
            out[0] = '\0';
            return 0;
        }    
    
        size_t i = 0;    
    
        // copy char to out until '\0' or i == n - 1
        for(i = 0; i < n - 1 && *str != '\0'; i++){
            out[i] = *str++;
        }    
    
        // deal with the trailing space
        while(isspace(out[--i]));    
    
        out[++i] = '\0';
        return i;
    }
    

提交回复
热议问题