思路:
这道题所有的操作均可使用 <string.h> 头文件中的库函数来完成。需要使用这三个库函数:
-
.substr()(截取字符串) -
.insert()(从中间插入子串) -
.
find()(查找子串)
同时,<string.h> 也重载了运算符:+=。
+= 与 .append() 库函数的用法是一样的,都是在指定字符串的后面插入新的字符串。
实现:
首先写出整体的代码框架,包括输入与判断(谁都会):
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
int n;
cin>>n>>s;
for(int i=0;i<n;i++){
int cz;
cin>>cz;//不是chen_zhe,是“操作”
switch (cz){
case 1:{
break;
}
case 2:{
break;
}
case 3:{
break;
}
case 4:{
break;
}
}
}
return 0;
}这道题最难的部分在于 4 个操作:
- 操作一:我们只需要使用
string重载后的 即可:
string tmp;
cin>>tmp;
s+=tmp;
cout<<s<<'\n';- 操作二:使用
substr函数,截取字符串:
int a,b;
cin>>a>>b;
s=s.substr(a,b);
cout<<s<<'\n';- 操作三:使用
insert函数,直接往字符串 的 处插入 字符串:
int a;
string tmp;
cin>>a>>tmp;
s.insert(a,tmp);
cout<<s<<'\n';- 操作四:
find函数可以直接查找子串,但要注意如果查找不到并不是直接返回 ,而是返回一个常量:std::string::npos,所以要加判断:
string tmp;
cin>>tmp;
int a=s.find(tmp);
if(a==(int)string::npos){
cout<<-1<<'\n';
}
else{
cout<<a<<'\n';
}最后附上全部代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
int n;
cin>>n>>s;
for(int i=0;i<n;i++){
int cz;
cin>>cz;//不是chen_zhe
switch (cz){
case 1:{
string tmp;
cin>>tmp;
s+=tmp;
cout<<s<<'\n';
break;
}
case 2:{
int a,b;
cin>>a>>b;
s=s.substr(a,b);
cout<<s<<'\n';
break;
}
case 3:{
int a;
string tmp;
cin>>a>>tmp;
s.insert(a,tmp);
cout<<s<<'\n';
break;
}
case 4:{
string tmp;
cin>>tmp;
int a=s.find(tmp);
if(a==(int)string::npos){
cout<<-1<<'\n';
}
else{
cout<<a<<'\n';
}
break;
}
}
}
return 0;
}