作者:嘛道理 | 来源:互联网 | 2023-06-01 03:27
在另一个数组中找到一个数组(byte)?在另一个byte[]中找到byte[]的最简单方法是什么?我有一种感觉,我可以用linq做,但我不知道如何。注意:我用[c#]搜索并没有找到
在另一个数组中找到一个数组(byte )?
在另一个byte []中找到byte []的最简单方法是什么? 我有一种感觉,我可以用linq做,但我不知道如何。
注意:我用[c#]
搜索并没有找到任何东西,我感到很惊讶。
这是一个简单(天真?)的方法:
static int search(byte[] haystack, byte[] needle) { for (int i = 0; i <= haystack.Length - needle.Length; i++) { if (match(haystack, needle, i)) { return i; } } return -1; } static bool match(byte[] haystack, byte[] needle, int start) { if (needle.Length + start > haystack.Length) { return false; } else { for (int i = 0; i
这是Ergwun出色答案的更快版本:
static int SearchBytes( byte[] haystack, byte[] needle ) { var len = needle.Length; var limit = haystack.Length - len; for( var i = 0; i <= limit; i++ ) { var k = 0; for( ; k
在一个11MB干草堆和9字节针的简短测试中,这大约快了三倍。
优化是:
当然对于长字节数组,你想要使用类似Boyer-Moore搜索的东西,但是出于很多目的,这样的简单算法已经足够好了,它具有简短易懂和validation的优点。
使用lambda表达式尝试这个:
private bool CheckPatternInArray(byte[] array, byte[] pattern) { int fidx = 0; int result = Array.FindIndex(array, 0, array.Length, (byte b) => { fidx = (b == pattern[fidx]) ? fidx + 1 : 0; return (fidx == pattern.Length); }); return (result >= pattern.Length - 1); }
如果您追求最快的,请在此处查看解决方案。
你可能自己想过这个,但有时我喜欢做简单的事情。
上述就是C#学习教程:在另一个数组中找到一个数组(byte )?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---编程笔记
bool found = false; int i = 0; for(; i