Remove extra white space from inside a C string?

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

    Edit: I originally had a malloced workspace, which I though might be clearer. However, doing it w/o extra memory is almost as simple, and I'm being pushed that way in comments and personal IMs, so, here comes...:-)

    void squeezespaces(char* row, char separator) {
      char *current = row;
      int spacing = 0;
      int i;
    
      for(i=0; row[i]; ++i) {
        if(row[i]==' ') {
          if (!spacing) {
            /* start of a run of spaces -> separator */
            *current++ = separator
            spacing = 1;
          }
        } else {
          *current++ = row[i];
          spacing = 0;
      }
      *current = 0;    
    }
    

提交回复
热议问题