standard c library for escaping a string

前端 未结 7 1944
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    You just mentioned that you wanted to print the string.

    char example[] = "first line\nsecond line: \"inner quotes\"";
    size_t len = strlen(example);
    size_t i;
    
    static const char *simple = "\\\'\"";
    static const char *complex = "\a\b\f\n\r\t\v";
    static const char *complexMap = "abfnrtv";
    
    for (i = 0; i < length; i++)
    {
        char *p;
        if (strchr(simple, example[i]))
        {
            putchar('\\');
            putchar(example[i]);
        }
        else if ((p = strchr(complex, example[i]))
        {
            size_t idx = p - complex;
            putchar('\\');
            putchar(complexMap[idx]);
        }
        else if (isprint(example[i]))
        {
            putchar(example[i]);
        }
        else
        {
            printf("\\%03o", example[i]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题