2013年计算机二级C语言上机题库四十五_第2页

考试站(www.examzz.com)   【考试站:中国教育考试第一门户】   2013年6月3日
  改错题
  下列给定程序中,函数fun的功能是:将s所指字符串中最后一次出现的t1所指子串替换成t2所指子串,所形成的新串放在w所指的数据中。在此处,要求t1和t2所指字符串的长度相同。
  例如,当s所指字符串中的内容为abcdabfabc,t1所指子串的内容为ab,t2所指子串中的内容为99时,结果,在w所指的数组中的内容为abcdabf99c。
  请改正程序中的错误,使它能得出正确的结果。
  注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
  #include <conio.h>
  #include <stdio.h>
  #include <string.h>
  /********found********/
  void fun(char* s, t1, t2, w)
  {
  char *p, *r, *a;
  strcpy(w, s);
  /********found********/
  while (w)
  {
  p = w;
  r = t1;
  while (*r)
  if (*r == *p)
  {
  r++;
  p++;
  }
  else
  {
  break;
  }
  if (*r == '\0')
  a = w;
  w++;
  }
  r = t2;
  while (*r)
  {
  *a = *r;
  a++;
  r++;
  }
  }
  main()
  {
  char s[100], t1[100], t2[100], w[100];
  printf("\nPlease enter string S:");
  scanf("%s", s);
  printf("\nPlease enter substring t1:");
  scanf("%s", t1);
  printf("\nPlease enter substring t2:");
  scanf("%s", t2);
  if (strlen(t1) == strlen(t2))
  {
  fun(s, t1, t2, w);
  printf("\nThe result is : %s\n", w);
  }
  else
  {
  printf("\nError : strlen(t1) != strlen(t2)\n");
  }
  }
  参考答案:1:void fun(char *s,t1,t2,w)应改为
  void fun(char *s,char *t1,char *t2,char *w)
  2:while(w)应改为while(*w)

相关文章