7-46 删除字符串中的子串_find()

输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。

输入格式:
输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。

输出格式:
在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。

输入样例:

Tomcat is a male ccatat
cat

输出样例:

Tom is a male 

代码

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

int main(){
	string s1,s2;
	int pos;
	getline(cin,s1);
	getline(cin,s2);
	while(s1.find(s2)!=-1)//只要能找到
	{
		pos=s1.find(s2);
		s1.erase(pos,s2.length());
	} 
	cout<<s1;
	return 0;
}

知识点

  1. find()
    说明:如果查找成功则输出查找到的第一个位置,否则返回-1;
    查找第一次出现的目标字符串:
    原文链接
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
	string s1 = "abcdef";
	string s2 = "de";
	int ans = s1.find(s2) ;   //在S1中查找子串S2
	cout<<ans<<endl;
	system("pause");
}
//输出:3

查找从指定位置开始的第一次出现的目标字符串:

#include<iostream>
#include<csdtio>
using namespace std;
int main(){
	string s1 = "abcdef";
	string s2 = "de";
	int ans = s1.find(s2, 2) ;   //从S1的第二个字符开始查找子串S2
	cout<<ans<<endl;
	system("pause");
}
//输出:3
  1. find_first_of()
    查找子串中的某个字符最先出现的位置
    find_first_of()不是全匹配,而find()是全匹配
#include<iostream>
#include<csdtio>
using namespace std;

int main(){
	string s1 = "adedef";
	string s2 = "dek";
	int ans = s1.find_first_of(s2) ;   //在S1中查找子串S2
	cout<<ans<<endl;
	system("pause");
}
//输出:1

也可以约定初始查找的位置:s1.find_first_of(s2, 2) ;

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

int main(){
	string s1 = "adedef";
	string s2 = "dek";
	int ans = s1.find_first_of(s2,2) ;   //在S1中查找子串S2
	cout<<ans<<endl;
	system("pause");
}
//输出2 
  1. find_last_of()
    这个函数与find_first_of()功能差不多,只不过find_first_of()是从字符串的前面往后面搜索,而find_last_of()是从字符串的后面往前面搜索。

  2. rfind()
    反向查找字符串,即找到最后一个与子串匹配的位置

  3. find_first_not_of()
    找到第一个不与子串匹配的位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DDouble-

你的鼓励是我最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值