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ș
2010-07-19 11:20:19
`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
2010-07-19 11:35:17
you're right. I forgot about it...
Cătălin Pitiș
2010-07-19 11:42:40
+2
A:
std::search
will find the first occurrence of one sequence inside another sequence.
Mike Seymour
2010-07-19 11:29:44
+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
2010-07-19 11:33:36
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
2010-07-19 13:02:15