#include "stdafx.h"
#include "stdio.h"
#include
int main()
{
char str[256],substr[256];
int count = 0;
printf("请输入字符串:");
scanf("%s",str);
printf("请输入子字符串:");
scanf("%s",substr);
count = findSubString(str,substr);
printf("%s出现在%s中的次数为:%d",substr,str,count);
getchar();
getchar();
return 0;
}
int findSubString(char *str,char *substr)
{
int substrLen =0,totalStrLen=0,cursor=0,count=0;
while(*str!='\0')
{
totalStrLen++;
str++;
}
str = str-totalStrLen;
while (*substr!='\0')
{
substrLen++;
substr++;
}
substr= substr-substrLen;
char *strVal = new char[substrLen+1];
strVal[substrLen]='\0';
while ((cursor+substrLen) < totalStrLen)
{
memcpy(strVal,str+cursor,substrLen);
if(strcmp(substr,strVal)==0)
{
count ++;
cursor += substrLen;
}
else
cursor++;
}
delete[] strVal;
return count;
}
建议用泛型算法,可直接用fine_first函数
参见c++primer