文本内容替换
程序代码:
// Note:Your choice is C++ IDE #include <sstream> #include <fstream> #include <string> #include <iostream> #include <vector> using namespace std; int nCount = 0; string& replaceAll(string& context, const string& from, const string& to) { size_t lookHere = 0; size_t foundHere; while((foundHere = context.find(from, lookHere)) != string::npos) { nCount++; context.replace(foundHere, from.size(), to); } return context; } int main() { ifstream ifile("g:\\123.txt"); string str; vector<string> text; string from; string to; int nSum = 0; cout<<"文本内容"<<str<<endl; while(getline(ifile, str)) { cout<<str<<endl; } ifile.close(); ifile.clear(); cout<<"请输入要替换的内容:"; cin>>from; cout<<"请输入要替换为的内容:"; cin>>to; ifile.open("g:\\123.txt"); while(getline(ifile, str)) { replaceAll(str, from, to); nSum += nCount; text.push_back(str); } ifile.close(); ifile.clear(); cout<<"共修改"<<nSum<<"处"<<endl; if(text.size()) { cout<<"替换后:"<<endl; ofstream ofile("g:\\123.txt"); for(int i = 0; i != text.size(); ++i) { ofile<<text[i]<<endl; cout<<text[i]<<endl; } ofile.close(); ofile.clear(); } else { cout<<"没有找到可以替换的!"; while(getline(ifile, str)) { cout<<str<<endl; } } return 0; }