机试 | STL | string | 文字处理软件

题目:

P5734 【深基6.例6】文字处理软件 - 洛谷

不使用库函数

#include
#include 
#include
using namespace std;

int main()
{
	int q;//第一行输入一个正整数q,表示操作次数
	string content;//第二行输入一个字符串str,表示最开始的字符串
	cin >> q;
	cin >> content;
	for (int i = 0; i < q; i++)
	{
		int flag;
		cin >> flag;//操作标志
		if (flag == 1)
		{
			string str;//插入字符串
			cin >> str;
			content = content + str;
			cout << content << endl;
		}
		else if (flag == 2)
		{
			int a;//截取起始位置
			int b;//截取长度
			cin >> a;
			cin >> b;
			string temp = content;
			content = "";
			//注意是a+b-1,从a开始(包括a)的b个字符
			for (int j = a; j <= a + b - 1; j++)
			{
				content += temp[j];
			}
			cout << content << endl;
		}
		else if (flag == 3)
		{
			int a;//插入位置
			string str;//插入字符串
			cin >> a;
			cin >> str;
			string temp;
			for (int k = 0; k < a; k++)
			{
				temp += content[k];
			}
			temp += str;
			for (int k = a; k < content.length(); k++)
			{
				temp += content[k];
			}
			content = temp;
			cout << content << endl;
		}
		else if (flag == 4)
		{
			string str;
			cin >> str;//查找字符串
			if (content.find(str) < content.length()) cout << content.find(str) << endl;
			else cout << -1 << endl;

		}
	}
	return 0;
}

使用库函数

  • find函数在找不到的时候会返回一个很大的数,长度大于字符串的长度,不是返回0
#include
#include
#include

using namespace std;

int main()
{
	int q;//操作次数
	string content;//最开始的字符串
	cin >> q;
	cin >> content;
	while (q)
	{
		int operation;//操作标志:1,2,3,4
		cin >> operation;
		//1 str:后接插入,在文档后面插入字符串 str,并输出文档的字符串;
		if (operation == 1)
		{
			string str;//后接插入的字符串
			cin >> str;
			content += str;
			cout << content << endl;
		}
		//2 a b:截取文档部分,只保留文档中从第 a 个字符起 b 个字符,并输出文档的字符串;
		else if (operation == 2)
		{
			int a, b;
			cin >> a >> b;
			string temp = content.substr(a, b);
			content = temp;
			cout << content << endl;
		}
		//3 a str:插入片段,在文档中第 a 个字符前面插入字符串 str,并输出文档的字符串;
		else if (operation == 3)
		{
			int a;
			string str;
			cin >> a >> str;
			content.insert(a, str);
			cout << content << endl;
		}
		//4 str:查找子串,查找字符串 str 在文档中最先的位置并输出;如果找不到输出 −1。
		else if (operation == 4)
		{
			string str;
			cin >> str;
			//找不到会返回一个诡异的数字,比字符串长
			//这里判断是否比长度小,防止异常输出
			if (content.find(str) < content.length()) cout << content.find(str) << endl;
			//这样会得到异常的输出,在找不到的时候,因为不是0,所以还是执行if,不会输出-1
			//if (content.find(str)) cout << content.find(str) << endl;
			else cout << -1 << endl;
		}
		q--;
	}
	return 0;
}

你可能感兴趣的:(c++,开发语言)