模拟strstr()函数

//题目出自:《程序员面试宝典》(第三版) 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值