Question:
Given two byte arrays, one representing the pattern and the other containing the data to be searched, determine where in the data array the pattern matches.
Solution:
The provided code provides an efficient and concise solution using the Locate extension method:
<code class="language-csharp">public static int[] Locate(this byte[] self, byte[] candidate) { if (IsEmptyLocate(self, candidate)) return Empty; var list = new List<int>(); for (int i = 0; i < self.Length; i++) { if (i + candidate.Length > self.Length) break; bool match = true; for (int j = 0; j < candidate.Length; j++) { if (self[i + j] != candidate[j]) { match = false; break; } } if (match) list.Add(i); } return list.ToArray(); } private static bool IsEmptyLocate(byte[] self, byte[] candidate) { return self == null || self.Length == 0 || candidate == null || candidate.Length == 0 || candidate.Length > self.Length; } private static readonly int[] Empty = new int[0];</code>
The Locate method iterates through the data array and checks how each possible starting position matches the pattern. If there is a match, record the position into the list; otherwise, continue to the next position.
Example:
<code class="language-csharp">// 示例字节数组 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 }; // 定位并打印匹配位置 foreach (var position in toBeSearched.Locate(pattern)) Console.WriteLine(position);</code>
This code slightly changes the original code to make it easier to understand and adds handling of empty arrays and cases where the pattern length is greater than the data length. IsEmptyLocate
Functions improve code readability and maintainability.
The above is the detailed content of How Can I Efficiently Find All Occurrences of a Byte Array Pattern within Another in C#?. For more information, please follow other related articles on the PHP Chinese website!