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

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

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

5条回答
  •  温柔的废话
    2021-01-18 01:52

    This works in my quick and dirty tests. Does it in place:

    #include 
    
    void strip(char *s) {
        char *p2 = s;
        while(*s != '\0') {
            if(*s != '\t' && *s != '\n') {
                *p2++ = *s++;
            } else {
                ++s;
            }
        }
        *p2 = '\0';
    }
    
    int main() {
        char buf[] = "this\t is\n a\t test\n test";
        strip(buf);
        printf("%s\n", buf);
    }
    

    And to appease Chris, here is a version which will make a place the result in a newly malloced buffer and return it (thus it'll work on literals). You will need to free the result.

    char *strip_copy(const char *s) {
        char *p = malloc(strlen(s) + 1);
        if(p) {
            char *p2 = p;
            while(*s != '\0') {
                if(*s != '\t' && *s != '\n') {
                    *p2++ = *s++;
                } else {
                    ++s;
                }
            }
            *p2 = '\0';
        }
        return p;
    }
    

提交回复
热议问题