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

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

    These functions will modify the original buffer, so if dynamically allocated, the original pointer can be freed.

    #include <string.h>
    
    void rstrip(char *string)
    {
      int l;
      if (!string)
        return;
      l = strlen(string) - 1;
      while (isspace(string[l]) && l >= 0)
        string[l--] = 0;
    }
    
    void lstrip(char *string)
    {
      int i, l;
      if (!string)
        return;
      l = strlen(string);
      while (isspace(string[(i = 0)]))
        while(i++ < l)
          string[i-1] = string[i];
    }
    
    void strip(char *string)
    {
      lstrip(string);
      rstrip(string);
    }
    
    0 讨论(0)
  • 2020-11-22 02:42

    Very late to the party...

    Single-pass forward-scanning solution with no backtracking. Every character in the source string is tested exactly once twice. (So it should be faster than most of the other solutions here, especially if the source string has a lot of trailing spaces.)

    This includes two solutions, one to copy and trim a source string into another destination string, and the other to trim the source string in place. Both functions use the same code.

    The (modifiable) string is moved in-place, so the original pointer to it remains unchanged.

    #include <stddef.h>
    #include <ctype.h>
    
    char * trim2(char *d, const char *s)
    {
        // Sanity checks
        if (s == NULL  ||  d == NULL)
            return NULL;
    
        // Skip leading spaces        
        const unsigned char * p = (const unsigned char *)s;
        while (isspace(*p))
            p++;
    
        // Copy the string
        unsigned char * dst = (unsigned char *)d;   // d and s can be the same
        unsigned char * end = dst;
        while (*p != '\0')
        {
            if (!isspace(*dst++ = *p++))
                end = dst;
        }
    
        // Truncate trailing spaces
        *end = '\0';
        return d;
    }
    
    char * trim(char *s)
    {
        return trim2(s, s);
    }
    
    0 讨论(0)
  • 2020-11-22 02:45

    I'm not sure what you consider "painless."

    C strings are pretty painful. We can find the first non-whitespace character position trivially:

    while (isspace(* p)) p++;
    

    We can find the last non-whitespace character position with two similar trivial moves:

    while (* q) q++;
    do { q--; } while (isspace(* q));
    

    (I have spared you the pain of using the * and ++ operators at the same time.)

    The question now is what do you do with this? The datatype at hand isn't really a big robust abstract String that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby's chomp function. What would such a function in C return?

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

    What do you think about using StrTrim function defined in header Shlwapi.h.? It is straight forward rather defining on your own.
    Details can be found on:
    http://msdn.microsoft.com/en-us/library/windows/desktop/bb773454(v=vs.85).aspx

    If you have
    char ausCaptain[]="GeorgeBailey ";
    StrTrim(ausCaptain," ");
    This will give ausCaptain as "GeorgeBailey" not "GeorgeBailey ".

    0 讨论(0)
  • 2020-11-22 02:47
    #include <ctype.h>
    #include <string.h>
    
    char *trim_space(char *in)
    {
        char *out = NULL;
        int len;
        if (in) {
            len = strlen(in);
            while(len && isspace(in[len - 1])) --len;
            while(len && *in && isspace(*in)) ++in, --len;
            if (len) {
                out = strndup(in, len);
            }
        }
        return out;
    }
    

    isspace helps to trim all white spaces.

    • Run a first loop to check from last byte for space character and reduce the length variable
    • Run a second loop to check from first byte for space character and reduce the length variable and increment char pointer.
    • Finally if length variable is more than 0, then use strndup to create new string buffer by excluding spaces.
    0 讨论(0)
  • 2020-11-22 02:48

    My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.

    void trim(char * s) {
        char * p = s;
        int l = strlen(p);
    
        while(isspace(p[l - 1])) p[--l] = 0;
        while(* p && isspace(* p)) ++p, --l;
    
        memmove(s, p, l + 1);
    }   
    

    This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().

    char * trim(char * s) {
        int l = strlen(s);
    
        while(isspace(s[l - 1])) --l;
        while(* s && isspace(* s)) ++s, --l;
    
        return strndup(s, l);
    }
    
    0 讨论(0)
提交回复
热议问题