【发布时间】:2014-05-26 19:31:27
【问题描述】:
我正在尝试编写一个函数,它将字符串中的所有转义序列转换为不可打印的形式。基本上,如果我有一个字符串“这个 \n 换行”,我希望它是“这个 换行”。到目前为止,我已经知道了。我从 main 调用:
int main()
{
unescape("This \\n\\n is \\t\\t\\t string number \\t 7.");
return 0;
}
char* unescape(char* s)
{
char *esc[2] = {"\\n", "\\t"};
int i;
char* uus = (char*)calloc(80, sizeof(char));
char* uus2 = (char*)calloc(80,sizeof(char));
strncpy(uus, s, strlen(s));
for(i = 0; i < 2; i++)
{
while(strstr(uus, esc[i]) != NULL) //checks if \\n can be found
{
//printf("\n\n%p\n\n", strstr(uus, esc[i]));
int c = strstr(uus, esc[i]) - uus; //gets the difference between the address of the beginning of the string and the location
//where the searchable string was found
uus2 = strncpy(uus2, uus, c); //copies the beginning of the string to a new string
//add check which esc is being used
strcat(uus2, "\n"); //adds the non-printable form of the escape sequence
printf("%s", uus2);
//should clear the string uus before writing uus2 to it
strncpy(uus, uus2, strlen(uus2)); //copies the string uus2 to uus so it can be checked again
}
}
//this should return something in the end.
}
基本上,我现在需要做的是从字符串 uus 中取出 "\n" 之后的部分并将其添加到字符串 uus2 中,这样我就可以再次运行 while 循环。我考虑过使用 strtok 但碰壁了,因为它使用某种分隔符创建两个单独的字符串,在我的情况下并不总是存在。
edit:将字符串的其余部分添加到 uus2 应该在 strncpy 之前。这是没有它的代码。
edit vol2:这是我最终使用的有效代码。基本上编辑了 Ruud 的版本,因为我必须使用的函数必须返回一个字符串。非常感谢。
char* unescape(char* s)
{
char *uus = (char*) calloc(80, sizeof(char));
int i = 0;
while (*s != '\0')
{
char c = *s++;
if (c == '\\' && *s != '\0')
{
c = *s++;
switch (c)
{
case 'n': c = '\n'; break;
case 't': c = '\t'; break;
}
}
uus[i] = c;
i++;
}
uus[i] = '\0';
return uus;
}
【问题讨论】:
-
您的原始代码至少存在 3 个问题:(1)您忙于来回复制数据,以至于忘记关闭这些转义字符留下的“漏洞”; (2) 你留下了未终止的字符串,因为
strncpy从未复制尾随\0; (3) 由于strcat(uus2, "\n");中的\n硬编码,\t被换行符替换。
标签: c string text-parsing arrays