使用 std 指令在文本文件中搜索单词
Search a word in a textfile using std instructions
我认为这不是一个困难的问题,但我想知道如何以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());
相关文章:
- 当您在此单词中搜索单词时调整字符数组的大小?
- 按单词搜索文件,然后在C++中打印特定行数
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 如何搜索向单词添加字母的所有可能组合?
- 搜索单词时的字母模式逻辑
- Xapian - 搜索查询不检索匹配项,除非将""添加到每个单词
- Qt C++macOS问题。我正在使用函数 .find( "a word") 在多集中搜索单词,它适用于 Windows 但不适用于 mac
- 如何使用二叉搜索计算搜索单词所需的时间
- 读取每个单词的文件,并使用二叉搜索树(词典)对这些单词进行排序
- C++ 在 CSV 文件中搜索单词
- 从文件搜索搜索单词,然后将整个行复制到另一个文件
- C++,用于在大文件中的行上搜索单词的算法
- 使用 std 指令在文本文件中搜索单词
- 如何在文本文件中的字符串中搜索单词
- 在搜索单词时使用问号来代表任何字符
- 在一个非常大的文件中搜索单词
- 在字符串文本(1-D数组/c++)中搜索单词
- 在两个文本文件中搜索单词
- 如何在文本文件中搜索单词,如果找到,请打印出整行
- 使用C在文本中搜索单词,并显示该单词后面的信息