standard c library for escaping a string

前端 未结 7 1948
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 17:51

Is there a standard C library function to escape C-strings?

For example, if I had the C string:

char example[] = \"first line\\nsecond line: \\\"inne         


        
7条回答
  •  借酒劲吻你
    2020-12-10 18:08

    There is no standard C library function for this.

    When you use the declaration

    char example[] = "first line\nsecond line: \"inner quotes\"";
    

    the escape sequences will be interpreted and replaced by the compiler. You will have to "un-interpret" the characters that C escapes. Here's a quick-n-dirty example:

    #include 
    #include 
    
    void print_unescaped(char* ptr, int len) {
        if (!ptr) return;
        for (int i = 0; i < len; i++, ptr++) {
            switch (*ptr) {
                case '\0': printf("\\0");  break;
                case '\a': printf("\\a");  break;
                case '\b': printf("\\b");  break;
                case '\f': printf("\\f");  break;
                case '\n': printf("\\n");  break;
                case '\r': printf("\\r");  break;
                case '\t': printf("\\t");  break;
                case '\v': printf("\\v");  break;
                case '\\': printf("\\\\"); break;
                case '\?': printf("\\\?"); break;
                case '\'': printf("\\\'"); break;
                case '\"': printf("\\\""); break;
                default:
                    if (isprint(*ptr)) printf("%c",     *ptr);
                    else               printf("\\%03o", *ptr);
            }
        }
    }
    

提交回复
热议问题