编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为asd asasdfg asd as zx67 asd mklo,子字符串为as,则应当输出6。 注意:部分源程序给出如下。 请勿改动主函数ma

admin2010-05-05  33

问题 编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为asd asasdfg asd as zx67 asd mklo,子字符串为as,则应当输出6。
   注意:部分源程序给出如下。
   请勿改动主函数main和具他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
   试题程序:
   #include <conio.h>
   #include <stdio.h>
   #include <string.h>
   int fun(char *str, char *substr)
   {
   }
   main ( )
   {
     char str[81],substr[3];
     int n;
     clrscr ();
     printf ("输入主字符串 ");
     gets (str);
     printf ("输入子字符串");
     gets (substr);
     puts (str);
     puts (substr);
     n=fun (shr, substr);
     printf("n=%d\n ",n);
   }

选项

答案int fun(char *str, char *substr) { int i, j=0; for(i=0;str[i+1]!=’\0’;i++) /*如果一个长度为2的子字符串在主字符串中出现一次,则j+1, 如此 循环*/ if (str [i]==substr [0] &&str [i+1]==substr [1] ) j++; return j; /*返回子字符串在主字符串中出现的次数*/ }

解析 该题中subsu只有两个字符,所以可以用if语句来直接进行判断。要注意if())中str组的下标为i和i+1,即比较当前字符及其以后的一个字符是否分别与substr中的字符对应相同,若都相同则表示出现了一次。
转载请注明原文地址:https://kaotiyun.com/show/uHID777K
0

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