C/C++中如何(un)转义字符串?

前端之家收集整理的这篇文章主要介绍了C/C++中如何(un)转义字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给定一个计数的字符串(一个字符数组或一个包装器,如std :: string),是否有一个“正确”的方法来在C或C中转义和/或解除它,这样“特殊”的字符(如null人物)成为C风格逃脱,“正常”人物保持原样?

或者我必须用手做吗?

解决方法

这是处理单个字符的功能
/*
** Does not generate hex character constants.
** Always generates triple-digit octal constants.
** Always generates escapes in preference to octal.
** Escape question mark to ensure no trigraphs are generated by repetitive use.
** Handling of 0x80..0xFF is locale-dependent (might be octal,might be literal).
*/

void chr_cstrlit(unsigned char u,char *buffer,size_t buflen)
{
    if (buflen < 2)
        *buffer = '\0';
    else if (isprint(u) && u != '\'' && u != '\"' && u != '\\' && u != '\?')
        sprintf(buffer,"%c",u);
    else if (buflen < 3)
        *buffer = '\0';
    else
    {
        switch (u)
        {
        case '\a':  strcpy(buffer,"\\a"); break;
        case '\b':  strcpy(buffer,"\\b"); break;
        case '\f':  strcpy(buffer,"\\f"); break;
        case '\n':  strcpy(buffer,"\\n"); break;
        case '\r':  strcpy(buffer,"\\r"); break;
        case '\t':  strcpy(buffer,"\\t"); break;
        case '\v':  strcpy(buffer,"\\v"); break;
        case '\\':  strcpy(buffer,"\\\\"); break;
        case '\'':  strcpy(buffer,"\\'"); break;
        case '\"':  strcpy(buffer,"\\\""); break;
        case '\?':  strcpy(buffer,"\\\?"); break;
        default:
            if (buflen < 5)
                *buffer = '\0';
            else
                sprintf(buffer,"\\%03o",u);
            break;
        }
    }
}

这是处理一个以null结尾的字符串(使用上面的函数)的代码

void str_cstrlit(const char *str,size_t buflen)
{
    unsigned char u;
    size_t len;

    while ((u = (unsigned char)*str++) != '\0')
    {
        chr_cstrlit(u,buffer,buflen);
        if ((len = strlen(buffer)) == 0)
            return;
        buffer += len;
        buflen -= len;
    }
}

猜你在找的C&C++相关文章