跳到正文

题解

题解:P5734 【深基6.例6】文字处理软件

cso666_Luogu约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月9日
篇幅
约 4 分钟
题目
P5734

版本

  1. v2当前
  2. v1

传送门


思路:

这道题所有的操作均可使用 <string.h> 头文件中的库函数来完成。需要使用这三个库函数:

  • .substr() (截取字符串)

  • .insert()(从中间插入子串)

  • . find() (查找子串)

同时,<string.h> 也重载了运算符:+=。

+= 与 .append() 库函数的用法是一样的,都是在指定字符串的后面插入新的字符串。

实现:

首先写出整体的代码框架,包括输入与判断(谁都会):

C++
#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 重载后的 +=+= 即可:
C++
string tmp;
cin>>tmp;
s+=tmp;
cout<<s<<'\n';
  • 操作二:使用 substr 函数,截取字符串:
C++
int a,b;
cin>>a>>b;
s=s.substr(a,b);
cout<<s<<'\n';
  • 操作三:使用 insert 函数,直接往字符串 ss 的 aa 处插入 tmptmp 字符串:
C++
int a;
string tmp;
cin>>a>>tmp;
s.insert(a,tmp);
cout<<s<<'\n';
  • 操作四:find 函数可以直接查找子串,但要注意如果查找不到并不是直接返回 −1-1,而是返回一个常量:std::string::npos,所以要加判断:
C++
string tmp;
cin>>tmp;
int a=s.find(tmp);
if(a==(int)string::npos){
cout<<-1<<'\n';
}
else{
cout<<a<<'\n';
}

最后附上全部代码:

C++
#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;
}
原文