// strstr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//*
int strlen(char *str)
{
int len=0;
while(*str)
{
str++;
len++;
}
return len;
}
bool strIsRepeat(char* str1,char* str2)
{
int i=0,j=0;
while(str1[i] && str2[j])
{
if(str1[i] ==str2[j])
{
i++;
j++;
}
else
return false;
}
if(str2[j]=='\0')
return true;
else
return false;
}
//实现strstr 函数。
int strstr(char str[], char par[])
{
int i=0;
int lengthDiff=(strlen(str)-strlen(par));
char *strtmp=NULL;
for(i=0;i<lengthDiff+1;i++)
{
strtmp=&str[i];
if(strIsRepeat(strtmp,par))
return i;
}
return -1;
}
/
//int j=0;
//while(str[i] && str[j])
//{
//if(str[i]==par[j])
//{
//++i;
//++j;
//}
//else
//{
//i=i-j+1;
//j=0;
//}
//}//while(str[i] && str[j])
// if(!str[j])
// return i-strlen(par);
// else
// return -1;
//}
//*/
//#include<string.h>
int main(int argc, char* argv[])
{
char str1[]="ABCDE";
char str2[]="ABC";
char str3[]="BCD";
char str4[]="CDE";
char str5[]="CDEFGF";
// printf("str2@str1:%s\n",strstr(str1,str2));
// printf("str3@str1:%s\n",strstr(str1,str3));
// printf("str4@str1:%s\n",strstr(str1,str4));
// printf("str5@str1:%s\n",strstr(str1,str5));
printf("str2@str1:%d\n",strstr(str1,str2));
printf("str3@str1:%d\n",strstr(str1,str3));
printf("str4@str1:%d\n",strstr(str1,str4));
printf("str5@str1:%d\n",strstr(str1,str5));
return 0;
}