jackhab
jackhab

Reputation: 17708

memmem() STL way?

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

Upvotes: 5

Views: 3773

Answers (4)

Hasturkun
Hasturkun

Reputation: 36422

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

Upvotes: 6

user195488
user195488

Reputation:

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

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254751

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

Upvotes: 2

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14327

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.

Upvotes: -1

Related Questions