使用C ++查找与文本匹配的行号

时间:2014-06-16 11:55:40

标签: c++

我想打开文件搜索字符串替换字符串,然后在最后打印替换后的字符串直到结束。

到目前为止,我已经使用

打开了文件
fstream file ("demo.cpp");

使用

while (getline (file,line))

但使用

string.find("something")

总是给我行号0,无论我在 find()

的参数中放入哪个字符串

我的问题是,在这种情况下我还可以使用其他内置函数吗?还是我必须手动搜索所有行?

2 个答案:

答案 0 :(得分:1)

要获得匹配发生的行号,您必须计算行数:

if (ifstream file("demo.cpp")) {
  int line_counter = 0;
  string line;
  while (getline (file,line) {
    line_counter++;
    if (line.find("something") != string::npos) {
      cout << 'Match at line ' << line_counter << endl;
    }
  }
} else {
  cerr << "couldn't open input file\n";
}

答案 1 :(得分:0)

您可以在每一行使用此replaceAll function,并将&#34;替换为文件功能&#34;建立在它之上。

我修改它以在发生替换时返回布尔值:

bool replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return false;
    size_t start_pos = 0;
    bool res = false;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
        res = true;
    }
    return res;
}

然后,剩下的就是:

  1. 迭代输入文件的所有行
  2. 查找并替换文件
  3. 上每次出现的字符串
  4. 如果发生替换,请写入行计数
  5. 将替换的字符串写在另一个文件上
  6. ReplaceInFile方法:

    void replaceInFile(const std::string& srcFile, const std::string& destFile,
                       const std::string& search, const std::string& replace)
    {
      std::ofstream resultFile(destFile);
      std::ifstream file(srcFile);
      std::string line;
      std::size_t lineCount = 0;
      // You might want to chech that the files are properly opened
      while(getline(file,line))
      {
        ++lineCount;
        if(replaceAll(line, search, replace))
          std::cout << "Match at line " << lineCount << " " << replace << std::endl;
        resultFile << line << std::endl;
      }
    }
    

    示例:

    int main()
    {
      replaceInFile("sourceFile.txt", "replaced.txt", "match", "replace");
      return 0;
    }