例如:我有阵列
var src = new byte[] {1, 2, 3, 4, 5};
var tag = new byte[] {3, 4};
Run Code Online (Sandbox Code Playgroud)
谁知道快速查找标签数组索引的方法?我需要以下内容:
int FindIndexOfSeq(byte[] src, byte[] sequence);
Run Code Online (Sandbox Code Playgroud)
一个序列在src中可以多次出现.
解决方案:如何查找列表中的子列表索引?
int FindIndexOfSeq<T>(byte[] src, byte[] tag)
{
Int32 tagCount = tag.Count();
// If `tag` is not empty and `src` contains `tag`
if (tagCount > 0 && src.Intersect(tag).Count() == tagCount)
{
// Find index of first element in `tag`
Int32 tagStartIndex = Array.IndexOf(src, tag.First());
// Get the matching slice of `tag` from `src`
var newSrc = src.Skip(tagStartIndex).Take(tag.Count()).ToList();
// Zip them together using their difference
var sum = Enumerable.Zip(tag, newSrc, (i1, i2) => Convert.ToInt32(i2 - i1)).Sum();
// If total of their differences is zero, both sequences match
if (sum == 0)
{
// return starting index of `tag` in `src`
return tagStartIndex;
}
}
// return `Not Found`
return -1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |