acm_VIM

acm_VIM
文章图片
题目.jpg

#include #include #include using namespace std; int n, sline, eline, pos_s, p1, p2, p3; char separator; string text[105], command, lastreplace, repla, replaceby; bool changed; void reget(int &s, int &e, string str) { //获取待替换文本范围 int p = str.find(','); s = 0; //获取起始行号 for (int i = 0; i < p; ++i) { s *= 10; s += str[i] - '0'; } e = 0; //获取终止行 for (int i = p + 1; i < str.size(); ++i) { e *= 10; e += str[i] - '0'; } }int main() { cin >> n; cin.get(); //输入换行符,保证getline()正常读取行 if (n == 0) return 0; //!! for (int i = 1; i <= n; ++i) getline(cin, text[i]); lastreplace = ""; int flag = 0; while (getline(cin, command)) { if (flag) cout << endl; //相邻两行间的空行 flag = true; pos_s = command.find('s'); if (pos_s == 2) {//%s,表示替换的范围是所有行 sline = 1; eline = n; } else { reget(sline, eline, command.substr(1, pos_s - 1)); } //因为分割符有多种可能,所以利用第一次找到的分隔符去寻找 //就不必知道分隔符具体是谁 separator = command[pos_s + 1]; //s后面便是分隔符 p1 = pos_s + 1; p2 = command.find(separator, p1 + 1); p3 = command.find(separator, p2 + 1); repla = command.substr(p1 + 1, p2 - p1 - 1); replaceby = command.substr(p2 + 1, p3 - p2 - 1); //如果pattern为空就使用上次不为空的pattern //而string是可以为空的 if (repla == "") repla = lastreplace; else lastreplace = repla; changed = false; int re_len = repla.size(), reby_len = replaceby.size(); for (int i = sline; i <= eline; ++i) { bool c = 0; int p = text[i].find(repla, 0); while (p != -1) { text[i].replace(p, re_len, replaceby); p = text[i].find(repla, p + reby_len); //从后面开始找,避免递归替换 changed = true; c = 1; } if (c) cout << setw(4) << i << "" << text[i] << endl; } if (!changed) cout << "Pattern not found" << endl; } system("pause"); return 0; }

    推荐阅读