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

后端 未结 30 2403
一个人的身影
一个人的身影 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条回答
  •  旧时难觅i
    2020-11-22 02:47

    #include 
    #include 
    
    char *trim_space(char *in)
    {
        char *out = NULL;
        int len;
        if (in) {
            len = strlen(in);
            while(len && isspace(in[len - 1])) --len;
            while(len && *in && isspace(*in)) ++in, --len;
            if (len) {
                out = strndup(in, len);
            }
        }
        return out;
    }
    

    isspace helps to trim all white spaces.

    • Run a first loop to check from last byte for space character and reduce the length variable
    • Run a second loop to check from first byte for space character and reduce the length variable and increment char pointer.
    • Finally if length variable is more than 0, then use strndup to create new string buffer by excluding spaces.

提交回复
热议问题