How to remove \n or \t from a given string in C?

后端 未结 5 1763
野性不改
野性不改 2021-01-18 01:27

How can I strip a string with all \\n and \\t in C?

5条回答
  •  囚心锁ツ
    2021-01-18 01:50

    I like to make the standard library do as much of the work as possible, so I would use something similar to Evan's solution but with strspn() and strcspn().

    #include 
    #include 
    #include 
    
    #define SPACE " \t\r\n"
    
    static void strip(char *s);
    static char *strip_copy(char const *s);
    
    int main(int ac, char **av)
    {
        char s[] = "this\t is\n a\t test\n test";
        char *s1 = strip_copy(s);
        strip(s);
        printf("%s\n%s\n", s, s1);
        return 0;
    }
    
    static void strip(char *s)
    {
        char *p = s;
        int n;
        while (*s)
        {
            n = strcspn(s, SPACE);
            strncpy(p, s, n);
            p += n;
            s += n + strspn(s+n, SPACE);
        }
        *p = 0;
    }
    
    static char *strip_copy(char const *s)
    {
        char *buf = malloc(1 + strlen(s));
        if (buf)
        {
            char *p = buf;
            char const *q;
            int n;
            for (q = s; *q; q += n + strspn(q+n, SPACE))
            {
                n = strcspn(q, SPACE);
                strncpy(p, q, n);
                p += n;
            }
            *p++ = '\0';
            buf = realloc(buf, p - buf);
        }
        return buf;
    }
    

提交回复
热议问题