//题目出自:《程序员面试宝典》(第三版) P227页 面试例题3
//模拟C++中的strstr函数,strstr1是书上的源代码,strstr2是自己编写的,略显臃肿,两者思想一样,实现细节有差别。
#include <iostream>
#include<string>
using namespace std;
//cs是主串,s是子串
const char* strstr2(const char* cs,const char* s)
{
int i=0,j=0;
int k=0;//2个字符串中相同子串长度
while(cs[i]!=NULL)
{
if(cs[i]==s[j]){
if(s[j+1]==NULL){
i=i-k;
return &cs[i];
}else{
++i;
++j;
++k;
}
}else{
i=i-k+1;//剔除str[i]
j=0;
k=0;
}//if
}//while
return NULL;
}
//s是主串,cs是子串
const char* strstr1(const char* s,const char* cs)
{
for(int i=0;s[i]!='\0';++i)
{
int j=0;
int temp=i;
if(s[i]==cs[j]){
while(s[i++]==cs[j++]){
if(cs[j]=='\0')
return &s[i-j];
}
i=temp;
}//if
}//for
return NULL;
}
int main()
{
char *cs="12355678";
char *s="6";
const char *res2=strstr2(cs,s);
if(res2==NULL)
cout<<"No"<<endl;
else
cout<<res2<<endl;
const char *res1=strstr(cs,s);
if(res1==NULL)
cout<<"No"<<endl;
else
cout<<res1<<endl;
return 0;
}
模拟strstr()函数
最新推荐文章于 2024-08-12 10:00:56 发布