字符串函数(5)strstr函数的使用和模拟实现

这两天军训,真是累死了。两天没写博客了,今天更新一篇字符串函数,这个strstr函数比前几个字符串函数难一点,我尽量写详细一点。

strstr函数

strstr函数的功能

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
The matching process does not include the terminating null-characters, but it stops there.
strstr函数的格式
char * strstr ( const char *, const char * );
写个代码看看吧

#include <stdio.h>
#include <string.h>
int main()
{
	char ch1[] = "i am student good student";
	char ch2[] = "student";
	char* ret = strstr(ch1, ch2);
	if (ret != NULL)
		printf("%s\n", ret);
	else
		printf("找不到");
	return 0;
}

这个代码很简单就不多解释了。下面开始讲strstr函数的模拟实现。

strstr函数的模拟实现

所有的解释都放在代码里面啦,大家要认真看哦,我很认真找写欸。
不知道assert(断言)const(常量)的就看往期的字符串博客咯。

#include <stdio.h>
#include <assert.h>
char* my_strstr(const char* str1, const char* str2)
{
	assert(*str1 && *str2);
	char* s1 = NULL;//si,s2的作用主要是代替str1和str2前进。使用了s1和s2就可以不改变str1和str2指向的东西,每一次循环重新将str1和str2赋给s1和s2就可以了。
	char* s2 = NULL;
	char* cp = str1;
	if (*str2 == '\0')//如果子字符串的为斜杠0,直接返回str1,规则是这样的。
		return str1;
	while (*cp)//用两个循环嵌套,第一个循环
	{
		s1 = cp;//cp的作用是记忆str1的位置,如果目的字符串为"abbbcd"子字符串为"bbc"记忆就显得极为重要了。当目的字符串中的bb对应子字符串中的bb,可是一旦再次加一,两个
		//字符串将不在相等,跳出第二个循环,此时cp++,再次回到一个循环,就可以完美打印出bbcd啦,其实可以给你们画图片的解释的,但是我相信大家都是很聪明的人,才不是我懒呢。
		s2 = str2;
		while (*s1 == *s2 && *s1 && *s2)//因为&&和数学上的且相似,*s1或*s2一但指向0就直接可以跳出循环了,这样写就比*s1!='\0'&&*s2!='\0'方便多了。
		{
			s1++;
			s2++;

		}
		if (*s2=='\0')//当*s2指向'\0'就证明s2走完了,可以直接返回cp了。
			return cp;
		cp++;

	}
	return NULL;//如果走上面的过程还是没有找到,就证明找不到了,直接返回空就是啦。
}
int main()
{
	char ch1[] = "i am a student good student";
	char ch2[] = "student";
	char* ret = my_strstr(ch1, ch2);
	if (ret != NULL)
		printf("%s\n", ret);
	else
		printf("找不到");
	return 0;
}

我是结衣,大一在读,如果发现错误就在评论区告诉我吧。期待你的关注哦。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yui_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值