Remove extra white space from inside a C string?

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

    You could read a line then scan it to find the start of each column. Then use the column data however you'd like.

    #include 
    #include 
    #include 
    
    #define MAX_COL 3
    #define MAX_REC 512
    
    int main (void)
    {
        FILE *input;
        char record[MAX_REC + 1];
        char *scan;
        const char *recEnd;
        char *columns[MAX_COL] = { 0 };
        int colCnt;
    
        input = fopen("input.txt", "r");
    
        while (fgets(record, sizeof(record), input) != NULL)
        {
            memset(columns, 0, sizeof(columns));  // reset column start pointers
    
            scan = record;
            recEnd = record + strlen(record);
    
            for (colCnt = 0; colCnt < MAX_COL; colCnt++ )
            {
              while (scan < recEnd && isspace(*scan)) { scan++; }  // bypass whitespace
              if (scan == recEnd) { break; }
              columns[colCnt] = scan;  // save column start
              while (scan < recEnd && !isspace(*scan)) { scan++; }  // bypass column word
              *scan++ = '\0';
            }
    
            if (colCnt > 0)
            {
                printf("%s", columns[0]);
                for (int i = 1; i < colCnt; i++)
                {
                 printf("#%s", columns[i]);
                }
                printf("\n");
            }
        }
    
        fclose(input);
    }
    

    Note, the code could still use some robust-ification: check for file errors w/ferror; ensure eof was hit w/feof; ensure entire record (all column data) was processed. It could also be made more flexible by using a linked list instead of a fixed array and could be modified to not assume each column only contains a single word (as long as the columns are delimited by a specific character).

提交回复
热议问题