深信服入职前编码训练21题--04


题目描述:

以下函数解析字符串str是否合法的C语言字符串字面值定义(不考虑八进制和十六进制字符编码),如果是,则将解码后的内容保存到buf中,并返回0,否则返回-1。比如,"hello \"sangfor\""解码后结果为hello "sangfor",请完成该函数代码:

int unescape_c_quoted(char *buf, const char *str){
    //TUDO
}

 

 

输入描述:

字符串

输出描述:

解码后的字符串
示例1
输入 "\"hello world\\n\\\"too\"" 输出 "hello world\n\"too"

 

解析: 只需要按照要求识别出转义字符,然后将字面值的转义字符替换为对应的ASCII码。

注意合法的字符串字面值开始和结尾必须用双引号括起来。

 

解答:

 1 #include <stdio.h>
 2 #include <malloc.h>
 3 #include <string.h>
 4 #include <ctype.h>
 5 
 6 int isOK(char c){  7     return (c=='\\' || c=='\"'||
 8             c=='\'' || c=='n' ||
 9             c=='t'  || c=='a' ||
10             c=='b'  || c=='f' ||
11             c=='r'  || c=='v'); 12 } 13 
14 char to(char c){ 15     if(c=='\\') return '\\'; 16     if(c=='\'') return '\''; 17     if(c=='\"') return '\"'; 18     if(c=='n')  return '\n'; 19     if(c=='a')  return '\a'; 20     if(c=='b')  return '\b'; 21     if(c=='f')  return '\f'; 22     if(c=='r')  return '\r'; 23     if(c=='t')  return '\t'; 24     if(c=='v')  return '\v'; 25     return 0; 26 } 27 
28 int unescape_c_quoted(char *buf, const char *str) 29 { 30     //TODO:
31     char *pbuf = buf; 32     const char *pstr = str+1; 33     while(*pstr!='\0'){ 34         *pbuf = *pstr; 35         if(*pstr=='\\' && *(pstr+1)!='\0' && isOK(*(pstr+1))){ 36             *pbuf = to(*(pstr+1)); 37             ++pstr; 38  } 39         ++pbuf; 40         ++pstr; 41  } 42     *(pbuf-1)='\0'; 43     return 0; 44 } 45 
46 int main() 47 { 48     char str[10000]; 49     char buf[10000]; 50     int len; 51 
52     if (fgets(str, sizeof(str), stdin) == NULL) { 53         fprintf(stderr, "input error\n"); 54         return 0; 55  } 56     len = strlen(str); 57     while (len > 0 && isspace(str[len - 1])) { 58         str[len - 1] = '\0'; 59         --len; 60  } 61     if(*str!='\"' || *(str+len-1)!='\"'){ 62         printf("error\n"); 63         return 0; 64  } 65  unescape_c_quoted(buf, str); 66     printf("%s\n", buf); 67     
68     fprintf(stderr, "input:%s\noutput:%s\n", str, buf); 69     return 0; 70 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM