我有一个字节数组:
BYTE Buffer[20000];
该数组包含以下数据:
00FFFFFFFFFFFF0010AC4C4053433442341401030A2F1E78EEEE95A3544C99260F5054A54B00714F8180B3000101010101010101010121399030621A274068B03600DA281100001C000000FF003457314D44304353423443530A000000FC0044454C4C2050323231300A2020000000FD00384B1E5310000A20202020202000FA
我的问题是如何在这个数组中搜索像“000000FC
”这样的模式?我真的不认为这很重要,但我也需要可以找到我的模式的索引。
最佳答案
因为你在 C++ 中,所以用 C++ 的方式来做:
char a[] = { 0, 0, 0, 0xFC };
char Buffer[20000] = ...
std::string needle(a, a + 4);
std::string haystack(Buffer, Buffer + 20000); // or "+ sizeof Buffer"
std::size_t n = haystack.find(needle);
if (n == std::string::npos)
{
// not found
}
else
{
// position is n
}
也可以使用算法直接搜索数组:
#include <algorithm>
#include <iterator>
auto it = std::search(
std::begin(Buffer), std::end(Buffer),
std::begin(a), std::end(a));
if (it == std::end(Buffer))
{
// not found
}
else
{
// subrange found at std::distance(std::begin(Buffer), it)
}
或者,在 C++17 中,您可以使用字符串 View :
std::string_view sv(std::begin(Buffer), std::end(Buffer));
if (std::size_t n = sv.find(needle); n != sv.npos)
{
// found at position n
}
else
{
// not found
}
关于c++ - 如何在 BYTE 数组中搜索模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7319391/