感谢用户 @chunk 为改进这个答案做出了贡献。
您为什么不编写通用解决方案?它会让你在未来避免很多问题。
char *
str_escape(char str[])
{
char chr[3];
char *buffer = malloc(sizeof(char));
unsigned int len = 1, blk_size;
while (*str != '\0') {
blk_size = 2;
switch (*str) {
case '\n':
strcpy(chr, "\\n");
break;
case '\t':
strcpy(chr, "\\t");
break;
case '\v':
strcpy(chr, "\\v");
break;
case '\f':
strcpy(chr, "\\f");
break;
case '\a':
strcpy(chr, "\\a");
break;
case '\b':
strcpy(chr, "\\b");
break;
case '\r':
strcpy(chr, "\\r");
break;
default:
sprintf(chr, "%c", *str);
blk_size = 1;
break;
}
len += blk_size;
buffer = realloc(buffer, len * sizeof(char));
strcat(buffer, chr);
++str;
}
return buffer;
}
它是如何工作的!
int
main(const int argc, const char *argv[])
{
puts(str_escape("\tAnbms\n"));
puts(str_escape("\tA\v\fZ\a"));
puts(str_escape("txt \t\n\r\f\a\v 1 \t\n\r\f\a\v tt"));
puts(str_escape("dhsjdsdjhs hjd hjds "));
puts(str_escape(""));
puts(str_escape("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\f\a\v"));
puts(str_escape("\x0b\x0c\t\n\r\f\a\v"));
puts(str_escape("\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14"));
}
输出
\tAnbms\n
\tA\v\fZ\a
txt \t\n\r\f\a\v 1 \t\n\r\f\a\v tt
dhsjdsdjhs hjd hjds
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ \t\n\r\f\a\v
\v\f\t\n\r\f\a\v
\a\b\t\n\v\f\r
此解决方案基于来自 Wikipedia https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences 的信息
以及 stackoverflow.com 的其他用户的答案。
测试环境
$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.6 (jessie)
Release: 8.6
Codename: jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.