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

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

    A bit late to the game, but I'll throw my routines into the fray. They're probably not the most absolute efficient, but I believe they're correct and they're simple (with rtrim() pushing the complexity envelope):

    #include 
    #include 
    
    /*
        Public domain implementations of in-place string trim functions
    
        Michael Burr
        michael.burr@nth-element.com
        2010
    */
    
    char* ltrim(char* s) 
    {
        char* newstart = s;
    
        while (isspace( *newstart)) {
            ++newstart;
        }
    
        // newstart points to first non-whitespace char (which might be '\0')
        memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\0' terminator
    
        return s;
    }
    
    
    char* rtrim( char* s)
    {
        char* end = s + strlen( s);
    
        // find the last non-whitespace character
        while ((end != s) && isspace( *(end-1))) {
                --end;
        }
    
        // at this point either (end == s) and s is either empty or all whitespace
        //      so it needs to be made empty, or
        //      end points just past the last non-whitespace character (it might point
        //      at the '\0' terminator, in which case there's no problem writing
        //      another there).    
        *end = '\0';
    
        return s;
    }
    
    char*  trim( char* s)
    {
        return rtrim( ltrim( s));
    }
    

提交回复
热议问题