使用 std 指令在文本文件中搜索单词

Search a word in a textfile using std instructions

本文关键字:搜索 单词 文件 文本 std 指令 使用      更新时间:2023-10-16

我认为这不是一个困难的问题,但我想知道如何以C++的方式做到这一点。我想搜索定义的单词或序列的位置。

我读了这篇文章堆栈类似的问题,答案看起来很棒。但是我不知道如何将此解决方案应用于文件。这个 std 指令很容易在 a 或 a 中应用,但我不知道如何应用于文件和序列。

指令:

std::ifstream file;
std::search(std::istreambuf_iterator<char>(file.rdbuf()) // search from here
          , std::istreambuf_iterator<char>()             // ... to here
          , pSignature                                   // looking for a sequence starting with this
          , pSignature+sigSize);                         // and ending with this

我可以使用字符串来存储要在文件中搜索的序列吗???

有人可以发布一个关于如何应用搜索指令的简单示例吗,我在编译它时总是犯大错误。

我不使用Windows,也不想使用Boost库。

提前谢谢。

将文件读入字符串(假设它不是很大)。 然后,您可以使用 string::find 或 std::algorithm。

using namespace std;
// read entire file into a string
ifstream file(".bashrc");
string contents((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
string needle = "export";
// search using string::find
size_t pos = contents.find(needle);
cout << "location using find: " << contents.find(needle) << endl;
// search using <algoritm>'s search
string::const_iterator it = search(contents.begin(), contents.end(), needle.begin(), needle.end());
cout << "location found using search: " << string(it, it + 10) << endl;
cout << "    at position: " << it - contents.begin() << endl;

[编辑]您也可以直接使用 istreambug_iterators 进行搜索,但这会使您拥有相同类型的迭代器。

istreambuf_iterator<char> it2 = search(
        istreambuf_iterator<char>(file), istreambuf_iterator<char>(),
        needle.begin(), needle.end());