C语言——strstr寻找字符子串

#include 
#include 
char* my_strstr(const char* p1, const char* p2)
{
	assert(p1 != NULL);
	assert(p2 != NULL);
	char *s1 = NULL;
	char *s2 = NULL;
	char* cur = (char*)p1;  //强制类型转换
	if (*p2 == '\0')
	{
		return (char*)p1;
	}
	while (*cur)  //记录起始地址
	{
		s1 = cur;
		s2 = (char*)p2;
		while ((*s1!='\0') && (*s2 != '\0') && (*s1 == *s2))  //s1不等于\0,s2不等于\0
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return cur;  //找到子串
		}
		cur++;
	}
	return NULL;  //找不到子串
}
int main()
{
	char* p1 = "abcdef";
	char* p2 = "def";
	char* ret = my_strstr(p1, p2);
	if (ret == NULL)
	{
		printf("子串不存在\n");
	}
	else
	{
		printf("%s\n", ret);  //打印出子串
	}
	return 0;
}

你可能感兴趣的:(c语言,算法,开发语言)