程序员面试宝典:模拟strstr()函数

請写一个函数来模拟c++中的strstr()函数:该函数的返回值是主串中子串及以后的字符全部返回

#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
using namespace std;

const char* str_str(const char* str_src,const char* str_set)
{
	int len1=strlen(str_src);
	int len2=strlen(str_set);
	int first;
	for(int i=0;i<len1;i++)
	{
		first=i;
		int k=0;
		while(str_src[k+i]==str_set[k] && k<len2)
			k++;
		if(k==len2)   return &str_src[first];		
	}
	return NULL;
}

int main()
{
	cout<<"Input the original string:";
	string str_src;
	cin>>str_src;
	cout<<"Input the substring:";
	string str_sub;
	cin>>str_sub;
	char *str1,*str2;
	str1=new char[str_src.length()+1];
	str2=new char[str_sub.length()+1];
	strcpy(str1,str_src.c_str());
	strcpy(str2,str_sub.c_str());
	cout<<str_str(str1,str2)<<endl;
	delete str1;
	delete str2;
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值