收到一个字符数组{150,150,150,37,0,56,0,105,105,105,150,150,150,67,58,32},怎样查找连续三个150出现的位置?求赐教

解决方案 »

  1.   

    google “连续子串”,这个是找连续的,你把代码中的连续改为相等就可
      

  2.   


            unsafe static void Main(string[] args)
            {
                byte[] chars = { 150, 150, 150, 37, 0, 56, 0, 105, 105, 105, 150, 150, 150, 67, 58, 32 };
                int x = BitConverter.ToInt32(new byte[] { 150, 150, 150, 0 }, 0);
                fixed (byte* p = chars)
                {
                    for (byte* q = p; q < p + chars.Length; q++)
                    {
                        if ((*(int*)q & 0x00ffffff) == x)
                            Console.WriteLine(q - p);
                    }
                }
                Console.ReadLine();
            }
      

  3.   


                byte[] chars = { 150, 150, 150, 37, 0, 56, 0, 105, 105, 105, 150, 150, 150, 67, 58, 32 };
                //将三个字节的150,150,150转为一个整数,方便在遍历时比较
                int x = BitConverter.ToInt32(new byte[] { 150, 150, 150, 0 }, 0);
                //得到数组chars的byte类型指针
                fixed (byte* p = chars)
                {
                    for (byte* q = p; q < p + chars.Length; q++)
                    {
                        //将byte类型指针q转为四字节整数指针,然后&0x00ffffff,这样该整数的三个低位字节如果是x的三个低位字节,计算结果就和x相同
                        if ((*(int*)q & 0x00ffffff) == x)
                            //计算出该字节在chars中的索引
                            Console.WriteLine(q - p);
                    }
                }
                Console.ReadLine();
      

  4.   

    如果用于对比的连续字符数多于四个,也可以定义一个结构体。另外纠正一下,上面的代码q < p + chars.Length应该改为q < p + chars.Length - 2。        [StructLayout(LayoutKind.Sequential)]
            struct Test
            {
                public byte a;
                public byte b;
                public byte c;
                public byte d;
                public byte e;
                public Test(byte aa, byte bb, byte cc,byte dd,byte ee)
                {
                    a = aa;
                    b = bb;
                    c = cc;
                    d = dd;
                    e = ee;
                }
            }
            static void Main(string[] args)
            {            byte[] chars = { 150, 150, 150, 37, 0, 56, 0, 105, 105, 150, 150, 150, 150, 150, 58, 32 };
                Test x = new Test(150, 150, 150, 150, 150);
                fixed (byte* p = chars)
                {
                    byte* m = p + chars.Length - sizeof(Test) + 1;
                    for (byte* q = p; q < m; q++)
                    {
                        if ((*(Test*)q).Equals(x))
                            Console.WriteLine(q - p);
                    }
                }
                Console.ReadLine();
            }