【C++】AOJ基础题 ITP1_9_D Transformation

Transformation

Write a program which performs a sequence of commands to a given string str. The command is one of:

  • print a b: print from the a-th character to the b-th character of str
  • reverse a b: reverse from the a-th character to the b-th character of str
  • replace a b p: replace from the a-th character to the b-th character of str with p

Note that the indices of str start with 0.

Input

In the first line, a string str is given. str consists of lowercase letters. In the second line, the number of commands q is given. In the next q lines, each command is given in the above mentioned format.

Output

For each print command, print a string in a line.

Constraints

  • 1≤ length of str ≤ 1000
  • 1 ≤ q ≤ 100
  • 0 ≤ ab < length of str
  • for replace command, ba + 1= length of p

Sample Input

xyz
3
print 0 2
replace 0 2 abc
print 0 2

Sample Output

xyz
abc

問題を解く

  • 最简单解法,reverse这里依然选择换下标。
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

char str[1001];
char re[1001];

char c1[] = "replace";
char c2[] = "reverse";
char c3[] = "print";

void replace(int a, int b)
{
	int count = 0;
	for (int i = a; i < b+1; i++)
	{
		str[i] = re[count];
		count++;
	}
}

void reverse(int a, int b)
{
	char temp = 0;
	int n = 0;
	if ((b - a + 1) % 2 == 0)
	{
		for (int i = a; i < ((b+a+1)/2); i++)
		{
			temp = str[i];
			str[i] = str[b - n];
			str[b - n] = temp;
			n++;
		}
	}
	else if ((b - a + 1) % 2 == 1)
	{
		for (int i = a; i < ((b+a+2) / 2); i++)
		{
			temp = str[i];
			str[i] = str[b - n];
			str[b - n] = temp;
			n++;
		}
	}

}

void print(int a, int b)
{
	for (int i = a; i < b + 1; i++)
	{
		cout << str[i];
	}
	cout << endl;
}


int main()
{
	int n = 0;
	int a = 0;
	int b = 0;

	cin >> str;
	cin >> n;

	for (int i = 0; i < n; i++)
	{
		char c[10];
		cin >> c;
		

		if (strcmp(c, c1) == 0)
		{
			cin >> a >> b >> re;
			replace(a, b);
		}
		else if (strcmp(c, c2) == 0)
		{
			cin >> a >> b;
			reverse(a, b);
		}
		else if (strcmp(c, c3) == 0)
		{
			cin >> a >> b;
			print(a, b);
		}
	}

	return 0;
}

A Good Try

  • 如果使用string类来写就太简单了,substr()、replace()、reverse()这几个方法信手拈来。
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

int main() {
	string str;
	int q;
	cin >> str;
	cin >> q;

	while (q--) {
		string s;
		cin >> s;
		if (s == "print") {
			int a, b;
			cin >> a >> b;
			cout << str.substr(a, b - a + 1) << endl;
		}
		else if (s == "reverse") {
			int a, b;
			cin >> a >> b;
			reverse(str.begin() + a, str.begin() + b + 1);
		}
		else {
			int a, b;
			string p;
			cin >> a >> b >> p;
			str.replace(a, b - a + 1, p);
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值