深信服入職前編碼訓練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