把字符串中制表符(‘\t')和换行符('\n')替换为字符串“\t”和“\n”。
不难,但是要注意最后要把目标字符串尾部加上’\0'结束符。
int main(void)
{
char *s = (char*)malloc(128);
strcpy(s, "Hello\tWorld. I'm a robot.\nNice to meet you.");
char *t = (char*)malloc(256);
txtEscape(s, t);
puts(t);
printf("\n");
return(0);
}
void txtEscape(char *s, char *t)
{
char ch;
int i=0, j=i;
while((ch=*(s+i++))!='\0')
{
switch(ch)
{
case '\n':
*(t+(j++)) = '\\';
*(t+(j++)) = 'n';
break;
case '\t':
*(t+(j++)) = '\\';
*(t+(j++)) = 't';
break;
default:
*(t+(j++)) = ch;
}
}
*(t+j)='\0';
}