有時可能會想要在byte數組中定位已知數組的位置(惡狠狠看了一眼某儀器文檔),以下代碼完成此功能: using System; using System.Collections.Generic; using System.Linq; namespace Hu { public class ByteM ...
有時可能會想要在byte數組中定位已知數組的位置(惡狠狠看了一眼某儀器文檔),以下代碼完成此功能:
using System; using System.Collections.Generic; using System.Linq; namespace Hu { public class ByteMatch { /// <summary> /// 返回源序列中首個與指定匹配序列相同的子序列後的第一個位元組在源序列中的索引,沒有匹配返回-1 /// </summary> /// <param name="source">源序列</param> /// <param name="match">匹配序列</param> /// <returns></returns> public static int IndexAfter(IEnumerable<byte> source, IEnumerable<byte> match) { if (null == source || null == match) throw new ArgumentNullException(); if (false == source.Any() || false == match.Any()) throw new ArgumentException("源序列與匹配序列都須包含數據"); int sLen = source.Count(), mLen = match.Count(); if (sLen < mLen) throw new ArgumentException("匹配序列長度大於源序列長度"); bool matched = false; int idx = 0, offset = 0; var lst = source.ToList(); while (sLen - offset >= mLen) { idx = lst.IndexOf(match.ElementAt(0), offset); if (-1 == idx) break; if (sLen - idx >= mLen) { matched = true; for (int jdx = 1; jdx < mLen; jdx++) { if (source.ElementAt(idx + jdx) != match.ElementAt(jdx)) { matched = false; break; } } if (false == matched) offset = idx + 1; else break; } else break; } return matched ? (idx + mLen) : -1; } } }View Code