函数介绍
函数功能:const char* strstr (const char* str1,const char* str2)
返回值:指向str1中指定的整个字符序列在str1中首次出现的指针,如果序列在str1中不存在,则为空指针。
函数示例
/* strstr example */
#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;
}
参考 cplusplus.com
函数逻辑
函数实现
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
const char* s1 = NULL;
const char* s2 = NULL;
//定义一个临时变量来记录查找原始目标函数str1
const char* position = str1;
while (*position)
{
s1 = position;
s2 = str2;
while (*s1!='\0'&&*s2!='\0'&& * s1 == *s2)//如果*str1和*str2都等于'\0'的话查找就没有意义了
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)position;
}
position++;
}
return NULL;
}
//模拟实习strstr(字符串查找)函数,它的返回值是char*
int main()
{
char arr1[] = "Welcome to the world of C language";
char arr2[] = "world";
char* ret=my_strstr(arr1, arr2);
if (ret == NULL)
{
printf("找不到");
}
else
{
printf("%s ", ret);
}
return 0;
}