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

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;
    }
    }

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改