c语言函数strstr分析

    xiaoxiao2021-04-13  27

    #include <string.h> char *strstr(const char *haystack, const char *needle); 功能:在字符串haystack中查找字符串needle出现的位置 参数: haystack:源字符串首地址 needle:匹配字符串首地址 返回值: 成功:返回第一次出现的needle地址 失败:NULL

    代码实现:

    #define CRT_SECURE_NO_WARNING #include <stdio.h> #include <stdlib.h> #include <string.h> char* my_strstr(const char *haystack, const char *needle) { int var; //等价于 if(*needle != '\0') if (*needle) { while (*haystack) { for (var=0;*(haystack+var)==*(needle+var);var++) { //查找下一个字符是否为字符串的结束符 if (!*(needle+var+1)) { return (char*)haystack; } } haystack++; } return NULL; } else { return (char*)haystack; } } int main(void) { char *src = "haha"; char *dst = "welcome to you"; char *var = NULL; system ("cls"); var =my_strstr (dst,src); if (var == NULL) { printf ("Sorry.Not found.\n"); } else printf ("%s\n",var); system("pause"); return 0; }

    测试效果:

    因为dst 里没有haha 字符串;所以提示Sorry. Not found 改为:char *src = "to";后;测试如下:

    转载请注明原文地址: https://ju.6miu.com/read-668339.html

    最新回复(0)