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

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

    Most of the answers so far do one of the following:

    1. Backtrack at the end of the string (i.e. find the end of the string and then seek backwards until a non-space character is found,) or
    2. Call strlen() first, making a second pass through the whole string.

    This version makes only one pass and does not backtrack. Hence it may perform better than the others, though only if it is common to have hundreds of trailing spaces (which is not unusual when dealing with the output of a SQL query.)

    static char const WHITESPACE[] = " \t\n\r";
    
    static void get_trim_bounds(char  const *s,
                                char const **firstWord,
                                char const **trailingSpace)
    {
        char const *lastWord;
        *firstWord = lastWord = s + strspn(s, WHITESPACE);
        do
        {
            *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE);
            lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE);
        }
        while (*lastWord != '\0');
    }
    
    char *copy_trim(char const *s)
    {
        char const *firstWord, *trailingSpace;
        char *result;
        size_t newLength;
    
        get_trim_bounds(s, &firstWord, &trailingSpace);
        newLength = trailingSpace - firstWord;
    
        result = malloc(newLength + 1);
        memcpy(result, firstWord, newLength);
        result[newLength] = '\0';
        return result;
    }
    
    void inplace_trim(char *s)
    {
        char const *firstWord, *trailingSpace;
        size_t newLength;
    
        get_trim_bounds(s, &firstWord, &trailingSpace);
        newLength = trailingSpace - firstWord;
    
        memmove(s, firstWord, newLength);
        s[newLength] = '\0';
    }
    

提交回复
热议问题