#include <stdio.h>
int mystrlen(const char *str)
{
int length = 0;
while (*str++)
{
length++;
}
return length;
}
char* mystrstr(const char *str, const char *sub) //寻找字串,找到则返回该地址
{
int n = 0;
if (sub != NULL)
{
while (*str)
{
for (n = 0; (*(str + n) == *(sub + n)); n++)
{
if (*(sub + n + 1) == '\0')
{
return (char *)str;
}
}
str++;
}
return NULL;
}
else
{
return (char *)str;
}
}
int Substring(char *str, const char *sub)
{
char *p = str;
int count = 0;
int sublen = mystrlen(sub);
p = mystrstr(p, sub); //在主串中寻找字串
while (p != NULL)
{
count++; //找到就计数器加1,让主串指针指向该字串之后一位继续寻找
p += sublen;
p = mystrstr(p, sub);
}
return count;
}
int main()
{
char str[100] = {0};
char sub[100] = {0};
int count = 0;
printf ("Please input a main string : \n"); //主串输入
scanf ("%s", str);
printf ("Please input a sub string : \n"); //字串输入
scanf ("%s", sub);
count = Substring(str, sub);
printf ("count = %d\n", count); //打印结果
return 0;
}