下列给定程序中,函数proc()的功能是:依次取出字符串中所有的数字字符,形成新的字符串,并取代原字符串。例如原始字符串是“ab45c6djfd789”,则输出后的字符是
“456789”。
请修改函数proc()中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>-
void proc(char*s)
{ int i,j;
for(i=0,j=0;s[i]!='\0 ';i++)
if(s[i]>='0 '&&s[i]<='9')
//****found****
s[j]=s[i];
//****found****
s[j]="\0":
}
void main()
{ char str[80];
system("CLS"):
printf("\nEnter a string:");gets(str);
printf("\n\nThe string is:%s\n",st r);
proc(str);
printf("{\n\nThe string of changing is:
%s\n",str);
}
参考答案
答案解析
(1)错误:s[i]=s[i]
正确:s[j++]=s[i]
(2)错误:s[j]="\0";
正确:s[j]='\0';
【解析】题目要求将字符串q-的数字字符形成新字符串并取代原字符串,每检查到一个数字字符,将其放在原字符串下标为0处开始存放,下标加1,因此“s[j]=s[i]”应改为“s[j++]=s[i]”。要使数字字符串成为独立的字符串,应该在数字字符串末尾加上结束符,字符串的结束符为'\0 ',因此“s[j]="\0"”应改为“s[j]='\0'”。