Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.
For example
byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}
My solution:
I tried various solutions and ended up modifying the SearchBytePattern one. I tested on a 30k sequence and it is, fast :)
Let me know your thoughts.
This is my propossal, more simple and faster:
Here's a simple code i wrote using only basic data types: (It returns the index of first occurance)
Jb Evain's answer has:
and then the IsMatch function first checks whether
candidate
goes beyond the length of the array being searched.This would be more efficient if the
for
loop were coded:at this point one could also eliminate the test from the start of
IsMatch
, so long as you contract via pre-conditions never to call it with "illegal' parameters.Why make the simple difficult? This can be done in any language using for loops. Here is one in C#: