C#二進位位元組流尋找函數IndexOf的範例程式碼詳解

來源:互聯網
上載者:User
C# 二進位位元組流尋找函數IndexOf

        /// <summary>        /// 報告指定的 System.Byte[] 在此執行個體中的第一個匹配項的索引。        /// </summary>        /// <param name="srcBytes">被執行尋找的 System.Byte[]。</param>        /// <param name="searchBytes">要尋找的 System.Byte[]。</param>        /// <returns>如果找到該位元組數組,則為 searchBytes 的索引位置;如果未找到該位元組數組,則為 -1。如果 searchBytes 為 null 或者長度為0,則傳回值為 -1。</returns>        internal int IndexOf(byte[] srcBytes, byte[] searchBytes)        {            if (srcBytes == null) { return -1; }            if (searchBytes == null) { return -1; }            if (srcBytes.Length == 0) { return -1; }            if (searchBytes.Length == 0) { return -1; }            if (srcBytes.Length < searchBytes.Length) { return -1; }            for (int i = 0; i < srcBytes.Length - searchBytes.Length; i++)            {                if (srcBytes[i] == searchBytes[0])                {                    if (searchBytes.Length == 1) { return i; }                    bool flag = true;                    for (int j = 1; j < searchBytes.Length; j++)                    {                        if (srcBytes[i + j] != searchBytes[j])                        {                            flag = false;                            break;                        }                    }                    if (flag) { return i; }                }            }            return -1;        }

使用樣本:

receiveData = new byte[1024];int receiveLen = socket.ReceiveFrom(receiveData, ref ep);receiveData = this.SubByte(receiveData, 0, receiveLen); if (this.IndexOf(receiveData, System.Text.Encoding.Unicode.GetBytes("Exec_Exit")) != -1){    this.runing = false;    break; }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.