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");
}