模拟实现C库函数strstr,strchr

strstr
char *strstr(const char *haystack, const char *needle)
功能: 在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 ‘\0’。
头文件: #include <string.h>
参数:haystack – 要被检索的 C 字符串。needle – 在 haystack 字符串内要搜索的小字符串。
返回值:该函数返回在 haystack 中第一次出现 needle 字符串的位置,如果未找到则返回 null。

     # include <stdio.h>
    # include <stdlib.h>
    # include <assert.h>
    char *mystrstr (const char* des ,const char *sour)
    {  
    	assert(*des);                            //判断指针是否有效
    	assert(*sour);
    	while (*des++!='\0')
    	{  
    	    char *d=(char *)des; 
    		while(*des==*sour)
    		{
    			des++;
    			sour++;
    		}
    	if (*sour==0)
    	return d;
    	}
    	return NULL;
    }
    int main ()
    {
    	char str1[]="i am a student";
    	printf ("%s\n",mystrstr (str1,"am"));
    	system("pause");
    	return 0;
    }

在这里插入图片描述

strchr
char * strchr(const char* _Str,int _Val)
头文件:#include <string.h>
功能:查找字符串_Str中首次出现字符_Val的位置
说明:返回首次出现_Val的位置的指针,返回的地址是被查找字符串指针开始的第一个与Val相同字符的指针,如果Str中不存在Val则返回NULL。
返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL

 # include <stdio.h>
 # include <stdlib.h>
 # include <assert.h>
 char *mystrchr(const char *dst,int c)
	{
		assert(*dst);
		while (*dst)
		{  
			 if (*dst==c)
	       {
			   return (char*)dst;
		   }
			 dst++;
		}
		  return NULL;
	}
	int main ()
	{
		char str[]="i am a student";
		printf ("%s\n",mystrchr(str,'m'));
		system ("pause");
		return 0;
	}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/QLH04_04/article/details/84259271