在 stream流 和 byte[] 中查找(搜索)指定字符串

这里注重看的是两个 Search 的扩展方法,一个是 stream 类型的扩展,另一个是 byte[] 类型的扩展,

如果大家有更好的“算法”,请给回复,我们一起优化!

-- 常用扩展代码,需要这部分代码的支持!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace Ims.Bll
{
  /// <summary>
  /// stream 、 string 、byte[] 间的转换扩展方法类
  /// </summary>
  public static class StreamExtend
  {
    #region Stream 扩展
    /// <summary>
    /// Stream Stream 转换为 byte 数组
    /// </summary>
    /// <returns></returns>
    public static byte[] ToByteArray(this Stream stream)
    {
      byte[] bytes = new byte[stream.Length];
      stream.Read(bytes, 0, bytes.Length);
      // 设置当前流的位置为流的开始
      stream.Seek(0, SeekOrigin.Begin);
      return bytes;
    }
    /// <summary>
    /// Stream 转换为 image 图片
    /// </summary>
    /// <returns></returns>
    public static Image ToImage(this Stream stream)
    {
      Image img = new Bitmap(stream);
      return img;
    }
    /// <summary>
    /// Stream 转换为 string ,使用 Encoding.Default 编码
    /// </summary>
    /// <returns></returns>
    public static string ToStr(this Stream stream)
    {
      return System.Text.Encoding.Default.GetString(stream.ToByteArray());
    }
    /// <summary>
    /// 在当前流中搜索指定的 byte[]
    /// </summary>
    /// <param name="arr"></param>
    /// <param name="key">搜索关键字</param>
    /// <param name="beginPosition">搜索开始位置</param>
    /// <returns>如果存在则返回byte[]在流中首次出现的位置,否则返回 -1</returns>
    public static long Search(this Stream stream, long beginPosition, byte[] key)
    {
      if (stream == null || stream.Length <= beginPosition)
        return -1;

if (key == null || stream.Length < key.Length)
        return -1;

long i=-1;
      long j = -1;
      int currentByte = int.MinValue;
      for(i=beginPosition;i<stream.Length;i++)
      {
        if (stream.Length < key.Length + i)
          break;

stream.Seek(i, SeekOrigin.Begin);
        for (j = 0; j < key.Length; j++)
        {
          currentByte = stream.ReadByte();
          if (currentByte != key[j])
            break;
        }
        if (j == key.Length)
          return i;

if(currentByte == -1)
          break;
      }
      return -1;
    }
    #endregion

#region byte[] 扩展
    /// <summary>
    /// byte[] 转换为 stream 流
    /// </summary>
    /// <returns></returns>
    public static Stream ToStream(this byte[] arr)
    {
      Stream stream = new MemoryStream(arr);
      // 设置当前流的位置为流的开始 www.2cto.com
      stream.Seek(0, SeekOrigin.Begin);
      return stream;
    }
    /// <summary>
    /// byte[] 转换为 Image
    /// </summary>
    /// <returns></returns>
    public static Image ToImage(this byte[] arr)
    {
      return Image.FromStream(arr.ToStream());
    }
    /// <summary>
    /// 转换为 string,使用 Encoding.Default 编码
    /// </summary>
    /// <returns></returns>
    public static string ToStr(this byte[] arr)
    {
      return System.Text.Encoding.Default.GetString(arr);
    }
    /// <summary>
    /// 搜索
    /// </summary>
    /// <param name="arr"></param>
    /// <param name="key">搜索关键字</param>
    /// <param name="beginPos">搜索开始位置</param>
    /// <returns></returns>
    public static int Search(this byte[] arr, int beginPosition, byte[] key)
    {
      if (arr == null || arr.Length <= beginPosition)
        return -1;

if (key == null || arr.Length < key.Length)
        return -1;

int i = -1;
      int j = -1;
      for (i = beginPosition; i < arr.Length; i++)
      {
        if (arr.Length < key.Length + i)
          break;

for (j = 0; j < key.Length; j++)
        {
          if (arr[i+j] != key[j])
            break;
        }
        if (j == key.Length)
          return i;
      }
      return -1;
    }
    #endregion

#region string 扩展
    /// <summary>
    /// string 转换为 byte[]
    /// </summary>
    /// <returns></returns>
    public static byte[] ToByteArray(this string str)
    {
      return System.Text.Encoding.Default.GetBytes(str);
    }
    /// <summary>
    /// string 转换为 Stream
    /// </summary>
    /// <returns></returns>
    public static Stream ToStream(this string str)
    {
      Stream stream = new MemoryStream(str.ToByteArray());
      // 设置当前流的位置为流的开始
      stream.Seek(0, SeekOrigin.Begin);
      return stream;
    }
    #endregion
  }
}

------------------------

-- 测试脚本

byte[] arr = "0123456789111".ToByteArray();
      byte[] key1 = "123".ToByteArray();
      byte[] key2 = "678".ToByteArray();
      byte[] key3 = "911".ToByteArray();
      byte[] key4 = "111".ToByteArray();
      //流内搜索测试
      Stream sm = arr.ToStream();
      long index1 = sm.Search(0, key1);
      long index2 = sm.Search(0, key2);
      long index3 = sm.Search(0, key3);
      long index4 = sm.Search(0, key4);
      //byte[]内搜索测试
      long index10 = arr.Search(0, key1);
      long index20 = arr.Search(0, key2);
      long index30 = arr.Search(0, key3);
      long index40 = arr.Search(0, key4);

-----

摘自 草青工作室 的专栏

原文转自:http://www.2cto.com/kf/201204/129171.html
请尊重原作者版权

在stream流和byte[]中查找(搜索)指定字符串的更多相关文章

  1. 如何在目录中查找具有指定字符串的文件(shell)

    find /tmp/ -name test.txt | xargs grep "hello" 可以查找到tmp目录下文件名test.txt并包含字符串hello的文件.

  2. 在某个目录下的所有文件中查找包含某个字符串的Windows命令

    findstr可以完成这个工作.   上面的命令表示,当前目录以及当前目录的所有子目录下的所有文件中查找"string"这个字符串. *.*表示所有类型的文件. /s 表示当前目录 ...

  3. mysql全库搜索指定字符串

    mysql全库搜索指定字符串 DELIMITER // DROP PROCEDURE IF EXISTS `proc_FindStrInAllDataBase`; # CALL `proc_FindS ...

  4. PHP判断字符串中是否包含指定字符串,支持中文哦

    RT,随手写的 /** * 判断字符串中是否包含指定字符串 * @var source 源字符串 * @var target 要判断的是否包含的字符串 * @return bool */ functi ...

  5. 将excel中某列数据中,含有指定字符串的记录取出,并生成用这个字符串命名的txt文件

    Python 一大重要的功能,就是可处理大量数据,那分不开的即是使用Excel表格了,这里我做下学习之后的总结,望对我,及广大同仁们是一个帮助Python处理Excel数据需要用到2个库:xlwt 和 ...

  6. ---iOS开发 截取字符串中两个指定字符串中间的字符串---

    例如,要截取一个字符串中,两个指定字符串中间的字符串,OC截取方法如下: // 要截取 "> 和 </ 之间的汉字内容: @implementationViewControlle ...

  7. PHP 查找二维数组中是否有指定字符串的字段

    Array ( ] => Array ( [content] => 您提交了订单,请等待系统确认 :: [operator] => 客户 ) ] => Array ( [con ...

  8. 在某OC字符串中,搜索指定的某字符串:-rangeOfString:

    NSString *originalStr = @"搜索:王者拜仁!"; NSString *subStr = @"搜索:"; // 在originalStr这 ...

  9. 在LoadRunner中查找和替换字符串

    参考<Search & Replace function for LoadRunner>: http://ptfrontline.wordpress.com/2009/03/13/ ...

随机推荐

  1. Ubuntu Kylin15下PHP环境的搭建(LAMP)

    Ubuntu下的PHP开发环境架设   今天重新装了ubuntu那么就吧过程记录下. 打开终端,也就是命令提示符. 我们先来最小化组建安装,按照自己的需求一步一步装其他扩展.命令提示符输入如下命令: ...

  2. 301重定向.htaccess规则(含二级目录跳转二级域名)

    301重定向是一种非常重要的"自动转向"技术.网址重定向最为可行的一种办法.当用户或搜索引擎向网站服务器发出浏览请求时,服务器返回的HTTP数据流中头信息(header)中的状态码 ...

  3. 网页中显示pdf

    1.<embed width="800" height="600" src="test_pdf.pdf"> </embed ...

  4. eclipse乱码解决方法

    eclipse之所以会出现乱码问题是因为eclipse编辑器选择的编码规则是可变的.一般默认都是UTF-8或者GBK,当从外部导入的一个工程时,如果该工程的编码方式与eclipse中设置的编码方式不同 ...

  5. 【2016-10-13】【坚持学习】【Day4】【virtual 虚函数】

    定义一个基类,有一个虚函数 定义三个子类,分别继承,重写,New,这个虚函数   abstract class Test { public virtual void Prinf() { Console ...

  6. CSS中单位px和em,rem的区别

    PX特点: 1 IE无法调整那些使用px作为单位的字体大小: 2. 国外的大部分网站能够调整的原因在于其使用了em或rem作为字体单位: 3. Firefox能够调整px和em,rem,但是96%以上 ...

  7. bzoj2548[Cstc2002]灭鼠行动

    Description 最近,有一些繁殖力很强的老鼠在下水道非常猖獗,灭鼠特工队正在计划消灭这些老鼠.下水道只有东西方向和南北方向的管道,如图所示. 灭鼠特工队的队员拥有强大的武器.他们将在某些时刻t ...

  8. C#几个经常用到的字符串截取

    C#几个经常用到的字符串截取 一. 1.取字符串的前i个字符 (1)string str1=str.Substring(0,i); (2)string str1=str.Remove(i,str.Le ...

  9. 修改linux的最大文件句柄数限制

                   在当前session有效,用户退出或者系统重新后恢复默认值       2)修改profile文件:在profile文件中添加:ulimit -n 65535      ...

  10. 实例讲解表单验证插件Validation的应用

    jquery.Validation是一款优秀的jquery插件,它能对客户端表单进行验证,并且提供了许多可以定制的属性和方法,良好的扩展性.现在 结合实际情况,我把项目中经常要用到的验证整理成一个实例 ...