Remove extra white space from inside a C string?

前端 未结 9 2304
心在旅途
心在旅途 2021-01-06 04:05

I have read a few lines of text into an array of C-strings. The lines have an arbitrary number of tab or space-delimited columns, and I am trying to figure out how to remove

9条回答
  •  一向
    一向 (楼主)
    2021-01-06 04:29

    I made a small improvment over John Bode's to remove trailing whitespace as well:

    #include 
    
    char *squeeze(char *str)
    {
      char* r; /* next character to be read */
      char* w; /* next character to be written */
      char c;
      int sp, sp_old = 0;
    
      r=w=str;
    
      do {
        c=*r;
        sp = isspace(c);
        if (!sp) {
          if (sp_old && c) {
            // don't add a space at end of string
            *w++ = ' ';
          }
          *w++ = c;
        }
        if (str < w) {
          // don't add space at start of line
          sp_old = sp;
        }
        r++;
      }
      while (c);
    
      return str;
    }
    
    #include 
    
    int main(void)
    {
      char test[] = "\t\nThis\nis\ta\f     test.\n\t\n";
      //printf("test = %s\n", test);
      printf("squeeze(test) = '%s'\n", squeeze(test));
      return 0;
    }
    

    br.

提交回复
热议问题