改进这段代码,输出每次单条指令执行后的字符串#include <iostream> #include <string> using namespace std; // 字符串类 class String { protected: string content; // 字符串内容 public: // 输入字符串 void input() { cin >> content; } // 返回字符串内容 string get_content() { return content; } // 返回字符串长度 int get_length() { return content.length(); } }; // 可编辑字符串类 class EditableString : public String { public: // 插入字符 void insert(int position, char c) { content.insert(position - 1, 1, c); } // 删除字符 void remove(int position) { content.erase(position - 1, 1); } // 替换字符 void replace(int position, char c) { content[position - 1] = c; } }; int main() { // 创建可编辑字符串对象 EditableString str; str.input(); // 输出原字符串 cout << "原字符串为:" << str.get_content() << endl; // 循环执行指令 while (true) { char command_type; int position; char c; // 输入指令 cin >> command_type; if (command_type == 'i') { cin >> position >> c; str.insert(position, c); } else if (command_type == 'd') { cin >> position; str.remove(position); } else if (command_type == 'r') { cin >> position >> c; str.replace(position, c); } else { break; } // 输出新字符串 cout << "新字符串为:" << str.get_content() << endl; } return 0; }
时间: 2024-02-06 21:04:01 浏览: 30
可以考虑将输出新字符串的代码放在循环外面,这样每次输出时不会重复输出原字符串。改进后的代码如下:
```
#include <iostream>
#include <string>
using namespace std;
// 字符串类
class String {
protected:
string content; // 字符串内容
public:
// 输入字符串
void input() {
cin >> content;
}
// 返回字符串内容
string get_content() {
return content;
}
// 返回字符串长度
int get_length() {
return content.length();
}
};
// 可编辑字符串类
class EditableString : public String {
public:
// 插入字符
void insert(int position, char c) {
content.insert(position - 1, 1, c);
}
// 删除字符
void remove(int position) {
content.erase(position - 1, 1);
}
// 替换字符
void replace(int position, char c) {
content[position - 1] = c;
}
};
int main() {
// 创建可编辑字符串对象
EditableString str;
str.input();
// 输出原字符串
cout << "原字符串为:" << str.get_content() << endl;
// 循环执行指令
while (true) {
char command_type;
int position;
char c;
// 输入指令
cin >> command_type;
if (command_type == 'i') {
cin >> position >> c;
str.insert(position, c);
} else if (command_type == 'd') {
cin >> position;
str.remove(position);
} else if (command_type == 'r') {
cin >> position >> c;
str.replace(position, c);
} else {
break;
}
}
// 输出新字符串
cout << "新字符串为:" << str.get_content() << endl;
return 0;
}
```