gpt4 book ai didi

c++ - 如何在 C/C++ 中(取消)转义字符串?

转载 作者:可可西里 更新时间:2023-11-01 15:59:04 40 4
gpt4 key购买 nike

给定一个counted 字符串(可以是字符数组,也可以是像std::string 这样的包装器),是否有一种“正确”的方式来转义和/或在 C 或 C++ 中对其进行转义,以便“特殊”字符(如空字符)变为 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, char *buffer, 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;
}
*buffer = '\0';
}

关于c++ - 如何在 C/C++ 中(取消)转义字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7369344/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com