模拟实现strstr
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strlen(char*dest)
{
int count = 0;
while (*dest!='\0')//计算字符串长度
{
count++;
dest++;
}
return count;
}
const int my_strstr(const char*arr, const char*dest) //因为只需要判断dest是否为arr的子集无需对其修改,因此用const修饰
{
assert(arr != NULL && dest != NULL);//断言 判断arr dest地址是否合法
int len = my_strlen(dest);//模拟函数strlen求dest字符串长度
int count = 0;//arr中含有的dest字符数用count计算
while (*arr)
{
while (*arr == *dest && *arr!='\0' && *dest!='\0')//判断arr dest 中对应字符是否相等
{
dest++;//地址向后一位继续比较
arr++;//
count++;//相等则+1
}
if (count == len)//表示arr中有子集dest
{
return 1; 返回1
}
arr++;//arr起始地址向后一位 //继续上述查找
}
return 0;//arr中不含有子集dest 返回0
}
int main()
{
char arr[30] = "abcdefg";
char dest[] = "abcd";
int ret=my_strstr(arr, dest);
if (ret == 1)
printf("Yes\n"); //arr中存在子集dest打印Yes
else
printf("No\n");//不存在打印No
system("pause");
}