在使用字符串的过程中,我们经常会用到转义字符,如’/?‘、‘//’、‘/'’……等等。对字符串中的转义字符进行操作时,有可能会误认为这是两个字符,需要我们根据转义的定义,将这两个字符转换为一个字符。其实完全不需要,因为对字符串进行操作时,计算机自动地将它们识别为一个字符。
#include "stdio.h"
int my_print_str (char* strPrnt)
{
int iCnt = 0;
while (*strPrnt)
{
/* 开始转义 */
if (*strPrnt == '\\')
{
switch (*++strPrnt)
{
case '\\':
putchar ('\\');
break;
case '\?':
putchar ('\?');
printf ("Function is here!\n");
break;
case '\'':
putchar ('\'');
break;
case '\"':
putchar ('\"');
break;
}
iCnt++;
strPrnt++;
}
else
{
putchar (*strPrnt);
iCnt++;
strPrnt++;
}
}
return iCnt;
}
int main ()
{
int len = my_print_str ("\?");
return 0;
}
我们认为的结果应该是:
[Running] gcc main.c -o main
?Function is here!
[Done] exited with code=0 in 4.487 seconds
实际的结果为:
[Running] gcc main.c -o main
?
[Done] exited with code=0 in 4.487 seconds
实际上,代码根本就没有进入"case '\?':"语句。