文件替换子字符串
#include <fstream>//ifstream读文件,ofstream写文件,fstream读写文件 #include <string>//文本对象,储存读取的内容 #include <iostream>//屏幕输出cout #include <cstdlib>//调用system("pause"); #include <windows.h>//用于函数SetConsoleOutputCP(65001);更改cmd编码为utf8 using namespace std; void replaceAllStr(string& str) { string strName = "stroke=\""; int nLenName = strName.length(); string strEnd = "\""; string strreplace = strName + string("black")+ strEnd +string(" "); int nReplacelen = strreplace.length(); string strTemp = str; string str2 = str; int nTotalIndex = 0; while (true) { int nPos1 = strTemp.find(strName); if (nPos1 == strTemp.npos) break; string strTemp2 = strTemp.substr(nPos1+ nLenName, strTemp.length()-(nPos1 + nLenName)); int nPos2 = strTemp2.find(strEnd); if (nPos2 == strTemp.npos) break; int strokeAlllen = (nPos2 + 1) + nLenName; nTotalIndex += nPos1; str.replace(nTotalIndex, strokeAlllen, strreplace); nTotalIndex += nReplacelen; strTemp = str.substr(nTotalIndex,str.length()- nTotalIndex); } } int main() { // string str = "12 stroke=\"12\">1234 stroke=\"3456\">12 stroke=\"12\">1234 stroke=\"3456\">12 stroke=\"12\">1234 stroke=\"3456\">12 stroke=\"12\">1234 stroke=\"3456\">"; // replaceAllStr(str); // cout << str << endl; // system("pause"); // return 0; GetTickCount() SetConsoleOutputCP(65001); ifstream in("D:\\clq\\weixin_file\\WXWork\\1688853094618981\\Cache\\File\\2020-10\\123\\14334451-1-40611184.svg"); string line; ofstream outfile("D:\\clq\\weixin_file\\WXWork\\1688853094618981\\Cache\\File\\2020-10\\123\\temp.svg"); if (in) // 有该文件 { while (getline(in, line)) // line中不包括每行的换行符 { // cout << "-------------------" << endl; // cout << line << endl; replaceAllStr(line); // if(line.find("") outfile << line << "\n"; // cout << line << endl; // cout << "-------------------" << endl; } } else // 没有该文件 { cout << "no such file" << endl; } outfile.close(); in.close(); system("pause"); return 0; }
void replaceAllStr2(string& str, string strName = "stroke=\"none\"", string strReplace = "stroke=\"black\"") { int strokeAlllen = strName.length(); int nReplacelen = strReplace.length(); string strTemp = str; int nTotalIndex = 0; while (true) { int nPos1 = strTemp.find(strName); if (nPos1 == strTemp.npos) break; nTotalIndex += nPos1; str.replace(nTotalIndex, strokeAlllen, strReplace); nTotalIndex += nReplacelen; strTemp = str.substr(nTotalIndex, str.length() - nTotalIndex); } } //示例调用 string str = "12 stroke=\"none\">1234 stroke=\"3456\">"; replaceAllStr2(str); cout << str << endl; system("pause");