09 04、05 实现mystrstr函数、strstr优化

09 04 实现mystrstr函数
09 05 strstr优化
觉得看代码快点,就是从功能的几种结果推条件,然后组合起来
不画图了,没合适的画法

01 自己写的

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mystrstr2(char* a, char* b)
{
	/*一开始的思路,三种情况:不匹配,半匹配,全匹配
	 全匹配
		strlen(b)
		a[i] == b[j]; i++; j++; count++; count == strlen(b); return &a[i];
	不匹配
		a[i] != b[j]; return NULL;
	半匹配
		a[i] == b[j]; count++; count != strlen(b); i++; j = 0;
	return NULL
 */
	int i = 0;//a计数
	int j = 0;//b计数
	int count = 0;//匹配计数
	while (a[i] != '\0') {
		if (a[i] == b[j]) {//字符匹配
			i++;//a前进
			j++;//b前进
			count++;//计数
			if (count == strlen(b))//够数
				return &a[i- strlen(b)];//返回够数的初始位置
		}
		else //字符不匹配
		{
			j = 0;//b清空
			count = 0;//计数清空
			i++;//a前进
		}
	}
	return NULL;//a结束了还不跳出,就是没了
}
void main()
{
	char* p = mystrstr2( "lwllor ll"," " );
	printf("%s\n", p);
	system("pause");
}

在这里插入图片描述

02 视频优化的。我减少了a的计数ta

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//和视频相比,少了一个a的计数tb
char* mystrstr(char* a, char* b)
{
	char* tb = b;//匹配计数
	while (*a)
	{
		while(*a == *tb)
		{
			a++;
			tb++;
		}
		if(*tb=='\0')//全匹配
			return a-strlen(b);
		else//半匹配
			tb=b;//计数清空
		a++;
	}
	return NULL;
}

void main()
{
	char* p = mystrstr( "hell oww","ell o" );
	printf("%s\n", p);
	system("pause");
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值