目录
strstr函数的功能
学习strstr函数编辑
使用strstr函数
模拟实现strstr函数
strstr函数的功能
在字符串 str1 中找 str2 字符串,如果在 str1 字符串中找到了 str2 字符串,就返回 str1 中找到的 dtr2 的地址,没找到的话就返回 NULL
举例说明:
字符串str1:"abcdefabcdef"
字符串str2:"fabc"
返回值以 %s 的形式打印:"fabcdef"
字符串str1:"abcdefabcdef"
字符串str2:"cbaf"
返回值以 %s 的形式打印:NULL
学习strstr函数
 
strstr函数的参数:
char* 类型的指针 str1 和 str2 ,所以需要传递的形参是两个字符串的首地址,并且只会在 str1 字符串中找 str2 字符串,并不会改变数据,所以可用 const 关键字修饰
strstr函数的返回值:
在 str1 字符串中找到了 str2 字符串时,返回 str1 字符串开始找到 str2字符串的首地址
没找到时,返回 NULL
使用strstr函数
str1 字符串中找到 str2 字符串时:
str1 字符串中没找到 str2 字符串时:
模拟实现strstr函数
const char* my_strstr(const char* str1, const char* str2)
{
	// 断言
	assert(str1 != NULL);
	assert(str2 != NULL);
	// 记录开始匹配的位置
	char* cp = str1;
	// 创建两个变动指针
	char* s1 = str1;
	char* s2 = str2;
	while (*s1 != NULL)
	{
		// 当 s1 和 s2 匹配不成功时,s1 重新赋值为 cp 最开始匹配的下一个位置
		s1 = cp;
		// 当 s1 和 s2 匹配不成功时,s2 重新赋值为 str2 字符串的起始位置
		s2 = str2;
		// 开始匹配
		while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
		{
			s1++;
			s2++;
		}
		// 匹配完时,当 s2 指向了 '\0' ,则说明匹配成功,返回匹配的记录位置
		if (*s2 == '\0')
			return cp;
		cp++;
	}
	// 当 str1 字符串都指向了 '\0' 时,表示 str1 字符串中没有 str2 字符串,返回 NULL 
	return NULL;
}![[CR]厚云填补_MSDA-CR](https://i-blog.csdnimg.cn/direct/11d8e4cf4b424dc28d79f22faf238cdd.png)


















