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 ≤ a ≤ b < length of str
- for replace command, b −a + 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;
}