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

后端 未结 30 1963
一个人的身影
一个人的身影 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.
    }
    
    0 讨论(0)
  • 2020-11-22 02:31

    The easiest way to skip leading spaces in a string is, imho,

    #include <stdio.h>
    
    int main()
    {
    char *foo="     teststring      ";
    char *bar;
    sscanf(foo,"%s",bar);
    printf("String is >%s<\n",bar);
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 02:31

    This is the shortest possible implementation I can think of:

    static const char *WhiteSpace=" \n\r\t";
    char* trim(char *t)
    {
        char *e=t+(t!=NULL?strlen(t):0);               // *e initially points to end of string
        if (t==NULL) return;
        do --e; while (strchr(WhiteSpace, *e) && e>=t);  // Find last char that is not \r\n\t
        *(++e)=0;                                      // Null-terminate
        e=t+strspn (t,WhiteSpace);                           // Find first char that is not \t
        return e>t?memmove(t,e,strlen(e)+1):t;                  // memmove string contents and terminator
    }
    
    0 讨论(0)
  • 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 <ctype.h>
    #include <string.h>
    
    /*
        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));
    }
    
    0 讨论(0)
  • 2020-11-22 02:35

    Use a string library, for instance:

    Ustr *s1 = USTR1(\7, " 12345 ");
    
    ustr_sc_trim_cstr(&s1, " ");
    assert(ustr_cmp_cstr_eq(s1, "12345"));

    ...as you say this is a "common" problem, yes you need to include a #include or so and it's not included in libc but don't go inventing your own hack job storing random pointers and size_t's that way only leads to buffer overflows.

    0 讨论(0)
  • 2020-11-22 02:35

    If you're using glib, then you can use g_strstrip

    0 讨论(0)
提交回复
热议问题