开发者

memmem() STL way?

开发者 https://www.devze.com 2023-01-08 09:28 出处:网络
Is there an STL algorithm which can be used to search a sequence of bytes inside a buffer lik开发者_开发技巧e memmem() does?I don\'t know if this is good code, but the following works, using std::sear

Is there an STL algorithm which can be used to search a sequence of bytes inside a buffer lik开发者_开发技巧e memmem() does?


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消