tags:

views:

204

answers:

4
+1  Q: 

memmem() STL way?

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

A: 

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.

Cătălin Pitiș
`strstr` would require you to zero-terminate the sequences, and wouldn't work if they can contain zeros. There is an algorithm: `std::search`.
Mike Seymour
you're right. I forgot about it...
Cătălin Pitiș
+2  A: 

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

Mike Seymour
+2  A: 

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

#include <cstdio>
#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+sizeof(match);

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

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

    return 0;
}
Hasturkun
A: 

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
0A0D