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

后端 未结 30 2355
一个人的身影
一个人的身影 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 
    
    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);
    }
    

提交回复
热议问题