memmem() STL 方式?

发布于 2024-09-10 18:31:57 字数 45 浏览 2 评论 0原文

是否有 STL 算法可用于像 memmem() 一样搜索缓冲区内的字节序列?

Is there an STL algorithm which can be used to search a sequence of bytes inside a buffer like memmem() does?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

掌心的温暖 2024-09-17 18:31:57

我不知道这是否是好的代码,但以下代码可以使用 std ::搜索

#include <cstdio>
#include <string.h>
#include <algorithm>

int main(int argc, char **argv)
{
    char *a = argv[0];
    char *a_end = a + strlen(a);
    char *match = "out";
    char *match_end = match+strlen(match); // If match contained nulls, you would have to know its length.

    char *res = std::search(a, a_end, match, match_end);

    printf("%p %p %p\n", a, a_end, res);

    return 0;
}

I don't know if this is good code, but the following works, using std::search:

#include <cstdio>
#include <string.h>
#include <algorithm>

int main(int argc, char **argv)
{
    char *a = argv[0];
    char *a_end = a + strlen(a);
    char *match = "out";
    char *match_end = match+strlen(match); // If match contained nulls, you would have to know its length.

    char *res = std::search(a, a_end, match, match_end);

    printf("%p %p %p\n", a, a_end, res);

    return 0;
}
吝吻 2024-09-17 18:31:57

std::search 将查找一个序列在另一个序列中的第一次出现。

std::search will find the first occurrence of one sequence inside another sequence.

空城之時有危險 2024-09-17 18:31:57

findsubstr 怎么样?

#include <string>
using std::string;
...
size_t found;

found = s.find("ab",4);
if (found != string::npos)
  finalString = s.substr(found); // get from "ab" to the end

What about find and substr?

#include <string>
using std::string;
...
size_t found;

found = s.find("ab",4);
if (found != string::npos)
  finalString = s.substr(found); // get from "ab" to the end
不醒的梦 2024-09-17 18:31:57

为什么不使用strstr?

没有实现任何算法。您可以实现自己的谓词以与 std::find_if 结合使用,但在我看来,这是过度设计的。

Why not use strstr?

There is no algorithm implemented. You could implement your own predicate to be used in combination with std::find_if, but it is overengineering, IMO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文