123-xiaoming 2020-07-02 09:28 采纳率: 25%
浏览 383
已采纳

C#中,在一个数组中检索在另一个数组,如果存在返回数组的位置,如果不存在返回-1,如何实现?

C# 实现

例如
byte[] newbyte=new byte[]{0x7E,0x20,0x30,0x2F,0x19,0x2C};
byte[] b=new byte[]{0x20,0x30};
检索数组b在数组newbyte中的位置,
理论上应该返回1

有什么方法可以实现这个功能吗?

  • 写回答

1条回答 默认 最新

  • qq_28838019 2020-07-02 10:37
    关注

    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 < needle.Length; i++)
    {
    if (needle[i] != haystack[i + start])
    {
    return false;
    }
    }
    return true;
    }
    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式