I cannot use strstr, memchr because array can contains any number of \0 chars, is there are any efficient ways to do that? I have to find all positions (indexes) or pointers.
4 Answers
Piece of cake in C++:
#include <string>
const std::string needle = get_byte_sequence();
const std::string haystack = get_data();
std::size_t pos = haystack.find(needle);
// found if pos != std::string::npos
Another option is to use a generic algorithm:
#include <algorithm>
std::string::const_iterator it = std::search(data.begin(), data.end(), needle.begin(), needle.end());
if (it != data.end())
{
// needle found at position std::distance(data.begin(), it);
}
else
{
// needle not found
}
Bear in mind that C++ string objects can contain arbitrary data. To create a string from a byte buffer, pass its size to the constructor:
char buf[200]; // fill with your data; possibly full of zeros!
std::string s(buf, 200); // no problem
7 Comments
Michael Krelin - hacker
I'd vote against the find, because it's not of the string nature it seems.
Kerrek SB
@MichaelKrelin-hacker: You think in such three-dimensional terms :-) Think of "string" as "string of bytes"; problem solved. Also, always think of "char" as "byte"; "char" is arguably the most inappropriately named data type...
Michael Krelin - hacker
I can think of char as byte, but I can't help thinking of char* as 0-terminated string ;-) But well, it all comes down to 3d terms - I used the word "nature" :) (and I used the words "vote against", though I didn't mean downvoting half of your answer:))
avakar
+1, except that
char buf[200]; is not full of zeroes (add initializer please).Kerrek SB
@avakar: Sorry, misunderstanding. I mean: "This is your data, possibly this is full of zeros."
|
memchr? There you give size of byte array so\0bytes isn't any problem.memmem.