且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中搜索并替换txt文件中的字符串

更新时间:2023-02-18 19:59:02

这应该有效.我使用string::find在每一行中找到所需的子字符串,并使用string::replace替换了发现的内容.

This should work. I used string::find to find the desired substring within each line, and string::replace to replace it if something has been found.

编辑:我忘记了单词每行出现多次的情况.添加了while来解决此问题.

I forgot about the case where the word occurs multiple times per line. Added a while to fix this.

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
    ifstream in(argv[1]);
    ofstream out(argv[2]);
    string wordToReplace(argv[3]);
    string wordToReplaceWith(argv[4]);

    if (!in)
    {
        cerr << "Could not open " << argv[1] << "\n";
        return 1;
    }

    if (!out)
    {
        cerr << "Could not open " << argv[2] << "\n";
        return 1;
    }

    string line;
    size_t len = wordToReplace.length();
    while (getline(in, line))
    {
        while (true)
        {
            size_t pos = line.find(wordToReplace);
            if (pos != string::npos)
                line.replace(pos, len, wordToReplaceWith);
            else 
                break;
        }

        out << line << '\n';
    }
}