如何将文件复制到另一个文件中,但是用用户输入的单词替换单词

How to copy a file into another file but replace a word with a user entered word?

本文关键字:文件 单词 用户 替换 输入 复制 另一个      更新时间:2023-10-16

我正在尝试将文件复制到另一个文件,但是用用户输入的内容更改单词。到目前为止,我已经想到了:

while (getline(openningTheFile, line, ' ')) //line is a string and openningTheFile is an ifstream 
{
    if (line == wordToBeDeleted)
    {
        line = wordToReplaceWith;
    }
    if (line == "n")
    {
        newFile << endl; //newFile is an ofstream 
    }
    newFile << line << " ";
}

,但问题在于此代码在"n"之后没有读取单词,因为定界符是空格。

有人可以将我指向正确的方向吗?

策略我建议:

  1. 使用std::getline读取线路。
  2. 寻找您想使用std::string::find在行中替换的字符串。
  3. 如果找到了,请用新字符串替换。
  4. 重复步骤2和3,直到找不到字符串为止。
  5. 输出更新的行。

这是为此的核心代码:

while (getline(openningTheFile, line)) 
{ 
   std::string::size_type pos;
   while ( (pos = line.find(wordToBeDeleted)) != std::string::npos )
   {
      line.replace(pos, wordToBeDeleted.length(), wordToReplaceWith);
   }
   newFile << line << 'n';
}

您正在使用std::getline读取文本的 line

您需要在文本行中找到单词,替换单词,然后将文本行写入输出文件。

一种方法是使用std::stringstream和操作员>>从字符串中提取单词。

另一个是使用std::string::find定位单词的位置。

您可以通过修改循环以使用 std::istringstream读取线条读取单词来做到这一点:

while (getline(openningTheFile, line)) 
{ 
    std::istringstream iss(line);
    std::string word;
    bool firstWord = true;
    while(iss >> word)
    {
        if(word == wordToBeDeleted) {  
            newFile << wordToReplaceWith;
            if(!firstWord) {
                newFile << " ";
            }
            firstWord = false;
        }
    }
    newFile << `n`;
}

这是一种解决方案,它使用boost :: iostreams的力量以高级但仍然非常灵活的方式解决任务。

对于OP的情况,这可能就像使用大锤锤破裂螺母一样,但是如果需要灵活性或必须处理更复杂的情况,则可能是正确的工具。

我正在使用与正则表达式结合的过滤流。这使我们可以在不创建任何中间字符串的情况下用替换字符串替换搜索模式。

#include <iostream>
#include <string>
#include <sstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/regex.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/regex.hpp>
namespace io = boost::iostreams;
using namespace std;
int main()
{ 
    // Your input "file" - you may replace it by an std::ifstream object.
    istringstream in( "why waste time learning learninglearning, when ignorance is instantaneous?" );
    // Search pattern and substitution string.        
    string findRegEx( R"(blearningb)" );
    string replaceStr( "sleeping" );
    // Build a regular expression filter and attach it to the input stream.
    io::filtering_istream inFiltered;
    inFiltered.push( io::regex_filter( boost::regex( findRegEx ), replaceStr ) );
    inFiltered.push( in );
    // Copy the filtered input to the output, replacing the search word on-the-fly.
    // Replace "cout" by your output file, e. g. an std::ofstream object.
    io::copy( inFiltered, cout );
    cout << endl;
}

live demo

输出:

why waste time sleeping learninglearning, when ignorance is instantaneous?

注意:

  • 实际的正则表达式为 blearningb
  • 我们不需要逃脱后斜线,因为我们使用了一个原始字符串字面。这样的东西非常整洁。
  • 正则表达式搜索整个单词"学习"(b表示一个单词边界)。这就是为什么它仅取代"学习"而不是"学习学习"的第一次事件。