Remove extra white space from inside a C string?

前端 未结 9 2310
心在旅途
心在旅途 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

    The following code modifies the string in place; if you don't want to destroy your original input, you can pass a second buffer to receive the modified string. Should be fairly self-explanatory:

    #include 
    #include 
    
    char *squeeze(char *str)
    {
      int r; /* next character to be read */
      int w; /* next character to be written */
    
      r=w=0;
      while (str[r])
      {
        if (isspace(str[r]) || iscntrl(str[r]))
        {
          if (w > 0 && !isspace(str[w-1]))
            str[w++] = ' ';
        }
        else
          str[w++] = str[r];
        r++;
      }
      str[w] = 0;
      return str;
    }
    
    int main(void)
    {
      char test[] = "\t\nThis\nis\ta\b     test.";
      printf("test = %s\n", test);
      printf("squeeze(test) = %s\n", squeeze(test));
      return 0;
    }
    

提交回复
热议问题