统计一个长度为n的字符串在另外一个字符串中出现的次数。
例如:假定输入字符串为helloworldhelloworld,子字符串为he,则应输出2
代码如下:
#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <string.h>int proc(char* ,char*);int main(){char str[81],sub[3];int n;system("CLS"); //<stdlib.h>printf("Input a main string : \n");gets(str);printf("Please input a sub string : \n");gets(sub);puts(str);puts(sub);n = proc(str,sub);printf("Output result is : %d\n",n);getch();}int proc(char* str,char* sub){int n;char* p,* r;n = 0;while (*str){p = str;r = sub;while (*r){if (*p == *r){p++;r++;}elsebreak;}if (*r == '\0')n++;str++;}return n;}
结果如下: