请补充函数fun(),该函数可以统计一个长度为n的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asd ascasdfg asd as asd mlosd,子字符串为asd,则应输出4。 注意:部分源程序给出如下。 请勿改动主函数

admin2009-02-15  36

问题 请补充函数fun(),该函数可以统计一个长度为n的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asd ascasdfg asd as asd mlosd,子字符串为asd,则应输出4。
   注意:部分源程序给出如下。
   请勿改动主函数main和其他函数中的任何内容,仅在函数fun()的横线上填人所编写的若干表达式或语句。
   试题程序:
            #include < stdio. h >
           #include < string. h >
           #include < conio. h >
           int fun(char * str,char * substr)
           {
              int n;
              char *p,*r;
                 (1);
        while( * str)
       {
         p = str;
         r = substr
         while( * r)
            if((2))
            {
               r++;
               p++;
            {
            else
               break;
          if((3))
            n++;
          str ++;
       }
       return n;
    }
    main( )
    {
       char str[81],substr[3];
       int n;
       clrscr ( );
       printf("输入主字符串:’);
       gets(str);
       printf(’输入子字符串:" );
       gets( substr );
       puts(str);
       puts(substr);
       n = fun(str,substr);
       printf("n=%d\n",n)
    }

选项

答案(1)n=0(2)*r==*p(3)*r==’\0’

解析 填空1:变量n用来记录子字符串在字符串中出现的次数,函数中对变量n进行了类型声明,但并没有进行初始化,所以此处对n初始化为0。填空2:进行比较时,如果子字符串的字符与字符串中的字符相同,则将两个字符串的指针都自加1,继续进行比较,否则跳出循环。填空3:如果此时指针r所指的字符为’\0’,则说明子字符串在字符串中出现了一次,将记录变量n加1。
转载请注明原文地址:https://jikaoti.com/ti/t2i7FFFM
0

相关试题推荐
最新回复(0)