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

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

    Here is how I do it. It trims the string in place, so no worry about deallocating a returned string or losing the pointer to an allocated string. It may not be the shortest answer possible, but it should be clear to most readers.

    #include 
    #include 
    void trim_str(char *s)
    {
        const size_t s_len = strlen(s);
    
        int i;
        for (i = 0; i < s_len; i++)
        {
            if (!isspace( (unsigned char) s[i] )) break;
        }
    
        if (i == s_len)
        {
            // s is an empty string or contains only space characters
    
            s[0] = '\0';
        }
        else
        {
            // s contains non-space characters
    
            const char *non_space_beginning = s + i;
    
            char *non_space_ending = s + s_len - 1;
            while ( isspace( (unsigned char) *non_space_ending ) ) non_space_ending--;
    
            size_t trimmed_s_len = non_space_ending - non_space_beginning + 1;
    
            if (s != non_space_beginning)
            {
                // Non-space characters exist in the beginning of s
    
                memmove(s, non_space_beginning, trimmed_s_len);
            }
    
            s[trimmed_s_len] = '\0';
        }
    }
    

提交回复
热议问题