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

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

    I didn't like most of these answers because they did one or more of the following...

    1. Returned a different pointer inside the original pointer's string (kind of a pain to juggle two different pointers to the same thing).
    2. Made gratuitous use of things like strlen() that pre-iterate the entire string.
    3. Used non-portable OS-specific lib functions.
    4. Backscanned.
    5. Used comparison to ' ' instead of isspace() so that TAB / CR / LF are preserved.
    6. Wasted memory with large static buffers.
    7. Wasted cycles with high-cost functions like sscanf/sprintf.

    Here is my version:

    void fnStrTrimInPlace(char *szWrite) {
    
        const char *szWriteOrig = szWrite;
        char       *szLastSpace = szWrite, *szRead = szWrite;
        int        bNotSpace;
    
        // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST
        while( *szRead != '\0' ) {
    
            bNotSpace = !isspace((unsigned char)(*szRead));
    
            if( (szWrite != szWriteOrig) || bNotSpace ) {
    
                *szWrite = *szRead;
                szWrite++;
    
                // TRACK POINTER TO LAST NON-SPACE
                if( bNotSpace )
                    szLastSpace = szWrite;
            }
    
            szRead++;
        }
    
        // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)
        *szLastSpace = '\0';
    }
    

提交回复
热议问题