文本文档中替换字符串
求一段代码
替换当前目录下指定名称的 TXT 文档中 特定字符串
如:将 当前目录下的名为 C1.TXT 中所有 “123ABCD123” 替换成 “456EFG456”
由于文本量比较大 最好要要比较效率高的
[解决办法]
ctrl + r 或者 H
替换 123ABCD123 456EFG456
[解决办法]
直接整个文件读进内存,CString有Replace方法,然后写回去。
这个数据量,没什么要考虑效率的吧。除非每分钟都要这么运行下。
[解决办法]
opendir, readdir , open, fstat, mmap, strstr, 替换字符串(涉及到后半段内存向前移动1字节,就你的例子来说,使用memmove)。
[解决办法]
#include<cstdlib>#include<string>#include<cstring>#include<fstream>using namespace std;void myreplace(const string& filename,const string& tofind,const string& toreplace){ ifstream fin(filename.c_str(),ios_base::binary); string str(1024*1024*2,0); fin.read(&str[0],2*1024*1024); fin.close(); ofstream fout(filename.c_str(),ios_base::binary); string::size_type beg=0,pos,find_size=tofind.size(),replace_size=toreplace.size(); while((pos=str.find(tofind,beg))!=string::npos) { fout.write(&str[beg],pos-beg); fout.write(&toreplace[0],replace_size); beg=pos+find_size; } fout.write(&str[beg],strlen(str.c_str())-beg); fout.close();}int main(){ myreplace("abca.txt","123ABCD123","456EFG456");}