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

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

    Here is my attempt at a simple, yet correct in-place trim function.

    void trim(char *str)
    {
        int i;
        int begin = 0;
        int end = strlen(str) - 1;
    
        while (isspace((unsigned char) str[begin]))
            begin++;
    
        while ((end >= begin) && isspace((unsigned char) str[end]))
            end--;
    
        // Shift all characters back to the start of the string array.
        for (i = begin; i <= end; i++)
            str[i - begin] = str[i];
    
        str[i - begin] = '\0'; // Null terminate string.
    }
    

提交回复
热议问题