gpt4 book ai didi

c++ - 使用标准指令在文本文件中搜索单词

转载 作者:行者123 更新时间:2023-11-27 23:23:42 25 4
gpt4 key购买 nike

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

我读了这篇文章 stack similar question答案看起来不错。但我不知道如何将此解决方案应用于文件。这个 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());

关于c++ - 使用标准指令在文本文件中搜索单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10906475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com