【问题标题】:How to locate subarray from an array c#如何从数组c#中定位子数组
【发布时间】:2014-12-27 10:07:50
【问题描述】:

我有以下字节数组。 byte[] subArray = { 0x00, 0x01, 0x00, 0x01 }; byte[] array = { 0x1A, 0x65, 0x3E, 0x00, 0x01, 0x00, 0x01, 0x2B, 0x4C, 0xAA };

我想识别子数组并将前面的字节加载到另一个字节数组中,即结果应该如下。 byte[] result = {0x2B, 0x4C, 0xAA }

我想加载子数组之后的所有内容。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 到目前为止你写了什么代码?您具体遇到了什么问题?
  • 即使您正在处理数组,这也可能会有所帮助:en.wikipedia.org/wiki/String_searching_algorithm
  • @Enigmativity 即将自己发布该链接。这与在字符串中搜索子字符串属于同一类型的问题。

标签: c#


【解决方案1】:

改编自我的other answer

byte[] subArray = { 0x00, 0x01, 0x00, 0x01 }; 
byte[] array = { 0x1A, 0x65, 0x3E, 0x00, 0x01, 0x00, 0x01, 0x2B, 0x4C, 0xAA };

var matchIndexes =
    from index in Enumerable.Range(0, array.Length - subArray.Length + 1)
    where array.Skip(index).Take(subArray.Length).SequenceEqual(subArray)
    select (int?)index;

var matchIndex = matchIndexes.FirstOrDefault();
if (matchIndex != null)
{
    byte[] successor = array.Skip(matchIndex.Value + subArray.Length).ToArray();
    // handle successor here
}

【讨论】:

  • 这就是为什么你有 25.6k 的声望?回答不费吹灰之力的“给我写代码”问题?
  • @KonradKokosa:我们是来回答问题的,而不是向 OP 灌输门徒。
  • @KonradKokosa SO 的重点不是任何特定的人——它正在为任何可以想象的编程问题建立一个永久的、易于搜索的答案库。任何人能够看到这一点并理解如何在数组中找到子数组所获得的价值,远远大于我们通过哄骗非姓名用户实际做作业所获得的价值。
【解决方案2】:

这个问题描述了如何在父数组中获取子数组的第一个索引。通过添加计数可以轻松修改以获取子数组的最后一个索引。从那里您可以使用 LINQ Take and Skip 或类似的数组操作函数。

Find the first occurrence/starting index of the sub-array in C#

【讨论】:

    【解决方案3】:

    一种方法是执行以下操作

    start from the first position 
     compare corresponding elements of array and sub array
      if there is a match 
        return the indexes as necessary and use the indexes to extract the result sets.
      else
        advance by 1 position
     repeat until you exhaust the whole main array
    

    您可以使用此方法在主数组中提取多组子数组。

    这是第一次剪辑。可能还有其他更有效的实现方式。

    【讨论】:

      【解决方案4】:

      试试这个。这段代码我没有测试,可能有一些语法错误,就算不行,试着理解一下算法。

          byte[] subArray = { 0x00, 0x01, 0x00, 0x01 }; 
          byte[] array = { 0x1A, 0x65, 0x3E, 0x00, 0x01, 0x00, 0x01, 0x2B, 0x4C, 0xAA };
          byte[] result;
      
          int lastLocation = -1;
          bool control = false;
      
          foreach(byte x in subArray)
          {
           if(array.contains(x))
           {
            if(location!=-1 || array.IndexOf(x) == lastLocation+1)
            {
             control = true;
             lastLocation = array.IndexOf(x);
            }
            else
            {
             control = false;
             lastLocation = -1;
            }
           }
           else
           {
           control = false;
           lastLocation = -1;
           }
          }
      if(control)
      {
      Array.Copy(array,lastLocation,result,0);
      }        
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多