memmem() STL way?

浪尽此生 提交于 2020-02-03 09:28:27

问题


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


回答1:


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;
}



回答2:


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




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/3280553/memmem-stl-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!