
strstr函数详解 看这一篇就够了
strstr()函数用于:查找子字符串
目录
函数介绍
用法示例
函数讲解
实现函数
事例展示
函数介绍函数声明:char *strstr(const char *str1, const char *str2)
头 文 件:#include <string.h> 返 回 值: 返回值为char * 类型( 返回指向 str1 中第一次出现的 str2 的指针);如果 str2 不是 str1 的一部分,则返回空指针。
用法示例 #include <stdio.h> #include <string.h> int main() { char str[] = "This is a simple string"; char* pch; pch = strstr(str, "simple"); if (pch != NULL) strncpy(pch, "sample", 6); puts(str); return 0; } 函数讲解 实现函数 char* My_strstr(const char* str1, const char* str2) { assert(str1 && str2); const char* s1 = str1; const char* s2 = str2; const char* p = str1; while (*p!='\\0') { s1 =p ; s2 = str2; while (*s1 != '\\0' && *s2 != '\\0' && *s1 == *s2) { s1++; s2++; } if (*s2 == '\\0') { return (char*)p; } p++; } return NULL; } 事例展示 #include <stdio.h> #include <string.h> #include<assert.h> char* My_strstr(const char* str1, const char* str2) { assert(str1 && str2); const char* s1 = str1; const char* s2 = str2; const char* p = str1; while (*p!='\\0') { s1 =p ; s2 = str2; while (*s1 != '\\0' && *s2 != '\\0' && *s1 == *s2) { s1++; s2++; } if (*s2 == '\\0') { return (char*)p; } p++; } return NULL; } int main() { char str[] = "This is a simple string"; char* pch; pch = My_strstr(str, "simple"); if (pch != NULL) strncpy(pch, "sample", 6); puts(str); return 0; }👁️ 阅读量:0
© 版权声明:本文《strstr函数详解 看这一篇就够了》内容均为本站精心整理或网友自愿分享,如需转载请注明原文出处:https://www.zastudy.cn/wen/1686495349a269866.html。