问答题 使用VC6打开考生文件夹下的源程序文件modi2.cpp。阅读下列函数说明和代码,补充空出的代码。函数convert(char*des*char*str,char c,char*str2)的功能是: 如果str中包含字符“!”,则替换成'a'; 如果str中包含字符“&”,则替换成'b'; 如果str中包含字符“*”,则替换成str2。 并用函数返回目标转换后的指针。 注意:只能补充函数convert(char*des.char*str,char*str2)。 #include #include #define MAXLEN 1024 void convert(char*des,char* str,char*str2) { } Void main() { char dest[MAXLEN]; char*str="!&cefghi*!&"; char*str2="jklm"; convert(dest,str,str2); cout<
【正确答案】正确答案:des[0]=0; char temp[2]={0,0); for(int i=0;str[i]!=NULL;i++) { if(str[i]=='!') { temp[0]='a'; //替换成'a' strcat(des,temp); } else if(str[i]=='&') { temp[0]='b'; strcat(des,temp); //替换成'b' } else if(str[i]=='*') { strcat(des,str2); //替换成str2 } else { temp[0]=str[i]; strcat(des,temp); //其他情况则添加在后面 } }
【答案解析】解析:(1)由审题分析可知,利用循环中不断检索str字符串每一个字符,循环变量i从0开始,直到到了sir字符结束,即srt[i]==NULL为循环判断结束条件。 (2)在循环体内,用ifelse语句判断是不是“!”、“&”或“*”这些特定的字符,如果是这些特定的字符则进行相应的替换,如果不是则将该字符直接加在des后面。 (3)字符串的连接可以使用字符串连接函数strcat(),将新字符连接在des后面,即strcat(des,temp)。