我的想法是使用队列来通过输入“寻找”。
static void Main(string[] args)
{
byte[] pattern = new byte[] { 3, 2, 1 };
byte[] data = new byte[] { 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1 };
foreach (long offset in FindPattern(pattern, data))
{
Console.WriteLine(offset);
}
Console.ReadLine();
}
public static IEnumerable<long> FindPattern(byte[] pattern, byte[] data)
{
Queue<byte> queue = new Queue<byte>(pattern.Length);
using (MemoryStream input = new MemoryStream(data))
using (BinaryReader reader = new BinaryReader(input))
{
byte[] buffer = new byte[1];
while (1 == reader.Read(buffer, 0, 1))
{
if (queue.Count == pattern.Length)
{
queue.Dequeue();
}
queue.Enqueue(buffer[0]);
if (Matches(queue, pattern))
{
// The input is positioned after the last read byte, which
// completed the pattern.
yield return input.Position;
}
}
}
}
private static bool Matches(Queue<byte> data, byte[] pattern)
{
return data.SequenceEqual(pattern);
}
我确定使用自定义的“队列”比SequenceEquals()执行更好的比较,但你明白了。
你真的应该发布一些相关规范和代码的更多细节。 –
我想你应该为此提出一个新问题。但是我不知道你的新代码做了什么,它似乎与你的原始问题没有关系:我没有看到任何模式在那里搜索。 – svick
阅读我在[这](http://stackoverflow.com/questions/6633793/c-sharp-pattern-search/38048944#38048944)问题答案的问题。 – eocron