将 c 字符串中的字符转换为其转义序列

2024-01-08

我需要一个像这样的函数字符串ToLiteral(字符串输入) from 这个帖子 https://stackoverflow.com/questions/323640/can-i-convert-a-c-string-value-to-an-escaped-string-literal。这样

char *literal = to_literal("asdf\r\n");

会产生文字==>“asdf\\r\\n”.

我用谷歌搜索了一下,但找不到任何东西(猜测我一定使用了错误的术语)。但是,我认为具有此功能的库一定存在于某个地方......

感谢您提供有趣的答案。顺便说一下,谷歌搜索“c string escape function”似乎是获得更多示例的关键,GLIB 提供了 g_strescape () ,这似乎正是我所需要的。


没有内置函数可以实现此目的,但您可以创建一个:

/* Expands escape sequences within a C-string
 *
 * src must be a C-string with a NUL terminator
 *
 * dest should be long enough to store the resulting expanded
 * string. A string of size 2 * strlen(src) + 1 will always be sufficient
 *
 * NUL characters are not expanded to \0 (otherwise how would we know when
 * the input string ends?)
 */

void expand_escapes(char* dest, const char* src) 
{
  char c;

  while (c = *(src++)) {
    switch(c) {
      case '\a': 
        *(dest++) = '\\';
        *(dest++) = 'a';
        break;
      case '\b': 
        *(dest++) = '\\';
        *(dest++) = 'b';
        break;
      case '\t': 
        *(dest++) = '\\';
        *(dest++) = 't';
        break;
      case '\n': 
        *(dest++) = '\\';
        *(dest++) = 'n';
        break;
      case '\v': 
        *(dest++) = '\\';
        *(dest++) = 'v';
        break;
      case '\f': 
        *(dest++) = '\\';
        *(dest++) = 'f';
        break;
      case '\r': 
        *(dest++) = '\\';
        *(dest++) = 'r';
        break;
      case '\\': 
        *(dest++) = '\\';
        *(dest++) = '\\';
        break;
      case '\"': 
        *(dest++) = '\\';
        *(dest++) = '\"';
        break;
      default:
        *(dest++) = c;
     }
  }

  *dest = '\0'; /* Ensure nul terminator */
}

请注意,我省略了“转义”字符的转义序列的翻译,因为这在 C 中没有标准化(一些编译器使用\e和其他人使用\x)。您可以添加适合您的内容。

如果您想要一个为您分配目标缓冲区的函数:

/* Returned buffer may be up to twice as large as necessary */
char* expand_escapes_alloc(const char* src)
{
   char* dest = malloc(2 * strlen(src) + 1);
   expand_escapes(dest, src);
   return dest;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 c 字符串中的字符转换为其转义序列 的相关文章

随机推荐