用STL最烦人的就是一个成员函数有多个重载版本,到底是写下标还是迭代器(一般不能同时出现在参数列表里),到底是一个参数还是两个参数等,希望熟练后有所改善
// #include <iostream> // #include <string> // #include <algorithm> // using namespace std; // // 翻转字符串的指定部分 // void reverseSubstring(string &s, int i, int len) { // reverse(s.begin() + i, s.begin() + i + len); // } // // 替换字符串的指定部分 // void replaceSubstring(string &s, int i, int len, const string &replacement) { // s.replace(i, len, replacement); // } // int main() { // string s; // while (cin >> s) { // 读取每组数据的字符串 // int n; // cin >> n; // 读取命令数量 // while (n--) { // string command; // cin >> command; // 读取命令 // int type = command[0] - '0'; // 命令类型(0或1) // int i = command[1] - '0'; // 起始下标 // int len = command[2] - '0'; // 操作长度 // if (type == 0) { // // 翻转操作 // reverseSubstring(s, i, len); // } // else if (type == 1) { // // 替换操作 // string replacement = command.substr(3); // 提取替换字符串 // replaceSubstring(s, i, len, replacement); // } // // 输出每次操作后的字符串 // cout << s << endl; // } // } // return 0; // } #include <string> #include <iostream> #include <algorithm> using namespace std; int main() { string str; int n; cin >> str >> n; while (n--) { string op; cin >> op; int begin = op[1] - '0';// 起始下标 int len = op[2] - '0'; // 要操作的字符串长度 if (op[0] == '0') { // 翻转,将首尾迭代器范围内左闭右开的字符全部翻转 reverse(str.begin() + begin, str.begin() + begin + len); } else if (op[0] == '1') { // 替换,第一个参数写要替换的起始下标,第二个参数写长度,第三个参数写目标字符串 str.replace(begin, len, op.substr(3)); } cout << str << endl; } return 0; }