簡體   English   中英

使用 C++ 替換文本文件中的單詞

[英]Replace a word in text file using 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;
   }

這段代碼對我的文件沒有任何影響,我猜原因是它只能更改整行,而不是部分字符串。 有人可以給我一些建議來正確實施嗎? 提前謝謝你。

從我閱讀原始問題的方式來看,您需要用“晚上”替換文件中所有“早上”的實例,而不僅僅是給定行上的一個實例。 我首先將整個文件讀入一個字符串。

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 剛剛注意到並解決了這個問題。

您可以取整行,然后搜索並替換子字符串。 這樣,您甚至可以跳過整個循環:

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");

有多種方法可以處理它。 一個很常見的做法是創建一個包含新字符串的文件,刪除舊文件,然后將新文件重命名為舊文件名。

如果這適合您,您可以使用此控制台應用程序。


參數 1 是要搜索的字符串

參數 2 是要使用的替換文本

參數3為文件路徑


基本上,我正在將一些 STD 流發送到新文件,並從舊文件中找到有問題的字符串是否存在,如果存在,則替換該字符串,然后通過管道傳輸結果,無論替換是否作為新文件發生新文件的行。

然后,我們關閉流,檢查文件大小,如果成功創建一個非空文件,我們將刪除舊文件並將新文件重命名為舊文件名。

如果退出代碼又名 errorlevel 為 2,則表示輸入流不起作用。 如果它是 -1,則意味着我們沒有成功找到並替換為完整的新文件。 如果為 1,則表示您沒有提供正確的參數。 只有零退出將表示成功。

如果你想使用它,你應該添加一些異常處理,並且可能是一個更強大的文件備份解決方案。

#include <iostream>
#include <fstream>
#include <string>
#include <sys\stat.h>

using namespace std;

int main(int argc, char * argv[])
{
    if (argc != 4) { return 1; }
    int exit_code = -1;

    string textToFind = string(argv[1]);
    string replacementText = string(argv[2]);
    string fileToParse = string(argv[3]);
    string fileToWrite = fileToParse+".rep";

    ifstream inputFileStream(fileToParse, ifstream::in);
    if (!inputFileStream.good()) { return 2; }

    ofstream outputFileStream(fileToWrite);

    string fileLine;
    while (getline(inputFileStream, fileLine))
    {
        size_t substringPos = fileLine.find(textToFind);
        if (substringPos != string::npos)
        {
            fileLine.replace(substringPos, textToFind.size(), replacementText);
        }       
        outputFileStream << fileLine << '\n';
    }
    outputFileStream.close();
    inputFileStream.close();

    struct stat st;
    stat(fileToWrite.c_str(), &st);
    int new_file_size = st.st_size;

    if (new_file_size > 0)
    {
        if (remove(fileToParse.c_str())==0)
        {
            if (rename(fileToWrite.c_str(), fileToParse.c_str())==0)
            {
                exit_code = 0;
            }
        }
    }

    return exit_code;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM