c# - 确定字节数组是否包含特定顺序的字节

标签 c# arrays comparison

<分区>

Possible Duplicate:
byte[] array pattern search

假设我有一个字节数组:

byte[] myArray = new byte[]{1,2,3,4,5,6,7,1,9,3,4,3,4,7,6,5,6,7,8};

如何确定 myArray 是否按顺序包含字节 9、3、4、3?我是否必须遍历数组,将每个元素附加到字符串,然后使用 String.Contains() 方法来了解该字节数组是否按顺序包含这些元素?

我知道我可以这样做:

String s = "";
foreach(byte b in myArray)
{
  s = s + b.ToString();
}

//then do  

s.Contains("9343")

这在长数组上效率不高。执行此操作的更有效方法是什么?

最佳答案

尝试以下操作

public static bool ContainsSequence(byte[] toSearch, byte[] toFind) {
  for (var i = 0; i + toFind.Length < toSearch.Length; i++) {
    var allSame = true;
    for (var j = 0; j < toFind.Length; j++) {
      if (toSearch[i + j] != toFind[j]) {
        allSame = false;
        break;
      }
    }

    if (allSame) {
      return true;
    }
  }

  return false;
}

关于c# - 确定字节数组是否包含特定顺序的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7546931/

相关文章:

c++ - 为什么我不必给函数数组的地址

r - 是什么使得这两个 R 数据帧不相同?

c# - C# 是否有某种 value_or_execute 或 value_or_throw?

c# - App.config 中的配置未正确提取

c - 如何在 C 中使用二维指针数组来存储字符串?

c++ - `bool operator<(Contact&)' 必须正好有两个参数

java - 为什么 String.equalsIgnoreCase 比较单个字符的大写和小写版本?

c# - 抽象类中的隐式转换

c# - 如何获取发送到 azure IoT 中心 c# 的设备总数和消息总数

java - 在 HashSet 中搜索字符串数组中的任意元素