使用c替换文本文件中的单词

新手上路,请多包涵

我正在寻找一种方法来使用 C++ 为我的 html 文件替换某个字符串(不是整行)。例如,如果我有一个包含以下内容的 html 文件:

 </span><br><span class=text>morning<br></span></td>

我希望它编辑为:

  </span><br><span class=text>night<br></span></td>

我需要用“晚上”替换“早上”,这是我的代码:

   string strReplace = "morning";
  string strNew = "night";
  ifstream filein("old_file.html");
  ofstream fileout("new_file.html");
  string strTemp;
  while(filein >> strTemp)
  {
    if(strTemp == strReplace){
       strTemp = strNew;
    }
    strTemp += "\n";
    fileout << strTemp;
   }

这段代码对我的文件没有任何影响,我猜原因是它只能更改整行,而不是部分字符串。有人可以给我一些建议以进行正确的实施吗?先感谢您。

原文由 Saintycer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 782
2 个回答

从我阅读原始问题的方式来看,您需要将文件中的所有“早晨”实例替换为“夜晚”,而不仅仅是给定行上的一个实例。我首先将整个文件读入一个字符串。

 std::string getfile(std::ifstream& is) {
  std::string contents;
  // Here is one way to read the whole file
  for (char ch; is.get(ch); contents.push_back(ch)) {}
  return contents;
}

接下来,制作一个 find_and_replace 函数:

 void find_and_replace(std::string& file_contents,
    const std::string& morn, const std::string& night) {
  // This searches the file for the first occurence of the morn string.
  auto pos = file_contents.find(morn);
  while (pos != std::string::npos) {
    file_contents.replace(pos, morn.length(), night);
    // Continue searching from here.
    pos = file_contents.find(morn, pos);
  }
}

然后主要是,

 std::string contents = getfile(filein);
find_and_replace(contents, "morning", "night");
fileout << contents;

编辑: find_and_replace() 不应将其 file_contents 字符串参数声明为 const 。刚刚注意到并解决了这个问题。

原文由 Jim Vargo 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以取整行,然后搜索并替换子字符串。这样,您甚至可以跳过整个循环:

 std::string line;

//Get line in 'filein'
std::getline(filein, line);

std::string replace = "morning";

//Find 'replace'
std::size_t pos = line.find(replace);

//If it found 'replace', replace it with "night"
if (pos != std::string::npos)
    line.replace(pos, replace.length(), "night");

原文由 Rakete1111 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏