strstr函数实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
//在s1中查找s2,并返回s2在s1中第一次出现的位置
char *strstr_bxy(const char *s1,const char *s2)
{
	assert(s1 != NULL && s2 != NULL);
	if(*s2 != '\0')
	{
		while(*s1 != '\0')
		{
			for(int n=0; *(s1+n) == *(s2+n); ++n)
			{
				if(*(s2+n+1) == '\0')
				{
					return (char *)s1;
				}
			}
			s1++;
		}
		return NULL;
	}
	else
	{
		return (char *)s1;
	}
}

void main()
{
	//输出NULL
	//const char *str1 = "abcdebcdf";
	//const char *str2 = "bd";

	//输出bcdebcdf
	//const char *str1 = "abcdebcdf";
	//const char *str2 = "bc";

	//触发断言,程序中止
	const char *str1 = "abcdebcdf";
	const char *str2 = NULL;


	char *c = strstr_bxy(str1,str2);
	if(c != NULL)
	{
		puts(c);
	}
	else
	{
		printf("NULL\n");
	}
}

你可能感兴趣的:(strstr函数实现)