Remove extra white space from inside a C string?

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

    Here's an alternative function that squeezes out repeated space characters, as defined by isspace() in . It returns the length of the 'squidged' string.

    #include 
    
    size_t squidge(char *str)
    {
        char *dst = str;
        char *src = str;
        char  c;
        while ((c = *src++) != '\0')
        {
            if (isspace(c))
            {
                *dst++ = ' ';
                while ((c = *src++) != '\0' && isspace(c))
                    ;
                if (c == '\0')
                    break;
            }
            *dst++ = c;
        }
        *dst = '\0';
        return(dst - str);
    }
    
    #include 
    #include 
    
    int main(void)
    {
        char buffer[256];
        while (fgets(buffer, sizeof(buffer), stdin) != 0)
        {
            size_t len = strlen(buffer);
            if (len > 0)
                buffer[--len] = '\0';
            printf("Before: %zd <<%s>>\n", len, buffer);
            len = squidge(buffer);
            printf("After:  %zd <<%s>>\n", len, buffer);
        }
        return(0);
    }
    

提交回复
热议问题