首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 位元組陣列查找函數 IndexOf 實作與使用範例

     編輯:關於C#

IndexOf 實作

/// 
/// 回傳指定 byte[] 在此實例中第一個符合項目的索引。
/// 
/// 被搜尋的 byte[]
/// 要搜尋的 byte[]
/// 找到則回傳索引;未找到或參數無效回傳 -1
internal int IndexOf(byte[] srcBytes, byte[] searchBytes) {
  if (srcBytes == null || searchBytes == null) return -1;
  if (srcBytes.Length == 0 || 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 match = true;
      for (int j = 1; j < searchBytes.Length; j++) {
        if (srcBytes[i + j] != searchBytes[j]) {
          match = false;
          break;
        }
      }
      if (match) 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;
}

接收資料後截取實際長度,搜尋「Exec_Exit」對應的 Unicode 位元組序列,找到則停止執行緒。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved