查找一个字节数组在另一个字节数组中出现的位置

作者:freethy 发布于:2013-3-18 15:56 Monday


        /// <summary>
        /// 查找字节数组 data2在data1中出现的位置
        /// </summary>
        /// <param name="data1"></param>
        /// <param name="data2"></param>
        /// <returns></returns>
        public int IndexOf(byte[] data1, byte[] data2)
        {
            for (int i = 0; i < data1.Length - data2.Length; i++)
            {
                //查找第一个索引
                bool gin = true;

                for (int j = 0; j < data2.Length; j += 1)
                {
                    if (data1[i + j] != data2[j])
                    {
                        gin = false;
                        break;
                    }
                }

                if (gin)
                {
                    return i;
                }
            }

            return -1;
        }

Powered by emlog 苏ICP备11068260号-3