在velocity优化时由于要将String转化为byte,所以就会涉及到一些针对byte数组的操作需要,如在一个数组中查找一个小数组、数组替换、数组扩展等操作,下面这个类就提供了这样一组方法,而且性能还不错。

package com.taobao.sketch.util;

import java.io.UnsupportedEncodingException;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.charset.Charset;

/**

* ArrayUtil,一些基于byte数组的操作方法集

*

* Author By: junshan

* Created Date: 2010-12-27 16:17:23

*/

public class ArrayUtil {

/**

* 查找并替换指定byte数组

*

* @param org of type byte[] 原数组

* @param search of type byte[] 要查找的数组

* @param replace of type byte[] 要替换的数组

* @param startIndex of type int 开始搜索索引

* @return byte[] 返回新的数组

* @throws UnsupportedEncodingException when

*/

public static byte[] arrayReplace(byte[] org, byte[] search, byte[] replace, int startIndex) throws UnsupportedEncodingException {

int index = indexOf(org, search, startIndex);

if (index != -1) {

int newLength = org.length + replace.length – search.length;

byte[] newByte = new byte[newLength];

System.arraycopy(org, 0, newByte, 0, index);

System.arraycopy(replace, 0, newByte, index, replace.length);

System.arraycopy(org, index + search.length, newByte, index + replace.length, org.length – index – search.length);

int newStart = index + replace.length;

//String newstr = new String(newByte, “GBK”);

//System.out.println(newstr);

if ((newByte.length – newStart) > replace.length) {

return arrayReplace(newByte, search, replace, newStart);

}

return newByte;

} else {

return org;

}

}

/**

* 从指定数组的copy一个子数组并返回

*

* @param org of type byte[] 原数组

* @param to 合并一个byte[]

* @return 合并的数据

*/

public static byte[] append(byte[] org, byte[] to) {

byte[] newByte = new byte[org.length + to.length];

System.arraycopy(org, 0, newByte, 0, org.length);

System.arraycopy(to, 0, newByte, org.length, to.length);

return newByte;

}

/**

* 从指定数组的copy一个子数组并返回

*

* @param org of type byte[] 原数组

* @param to 合并一个byte

* @return 合并的数据

*/

public static byte[] append(byte[] org, byte to) {

byte[] newByte = new byte[org.length + 1];

System.arraycopy(org, 0, newByte, 0, org.length);

newByte[org.length] = to;

return newByte;

}

/**

* 从指定数组的copy一个子数组并返回

*

* @param org of type byte[] 原数组

* @param from 起始点

* @param append 要合并的数据

*/

public static void append(byte[] org, int from, byte[] append) {

System.arraycopy(append, 0, org, from, append.length);

}

/**

* 从指定数组的copy一个子数组并返回

*

* @param original of type byte[] 原数组

* @param from 起始点

* @param to 结束点

* @return 返回copy的数组

*/

public static byte[] copyOfRange(byte[] original, int from, int to) {

int newLength = to – from;

if (newLength < 0)

throw new IllegalArgumentException(from + ” > ” + to);

byte[] copy = new byte[newLength];

System.arraycopy(original, from, copy, 0,

Math.min(original.length – from, newLength));

return copy;

}

public static byte[] char2byte(String encode, char… chars) {

Charset cs = Charset.forName(encode);

CharBuffer cb = CharBuffer.allocate(chars.length);

cb.put(chars);

cb.flip();

ByteBuffer bb = cs.encode(cb);

return bb.array();

}

/**

* 查找指定数组的起始索引

*

* @param org of type byte[] 原数组

* @param search of type byte[] 要查找的数组

* @return int 返回索引

*/

public static int indexOf(byte[] org, byte[] search) {

return indexOf(org, search, 0);

}

/**

* 查找指定数组的起始索引

*

* @param org of type byte[] 原数组

* @param search of type byte[] 要查找的数组

* @param startIndex 起始索引

* @return int 返回索引

*/

public static int indexOf(byte[] org, byte[] search, int startIndex) {

KMPMatcher kmpMatcher = new com.taobao.sketch.util.ArrayUtil.KMPMatcher();

kmpMatcher.computeFailure4Byte(search);

return kmpMatcher.indexOf(org, startIndex);

//return com.alibaba.common.lang.ArrayUtil.indexOf(org, search);

}

/**

* 查找指定数组的最后一次出现起始索引

*

* @param org of type byte[] 原数组

* @param search of type byte[] 要查找的数组

* @return int 返回索引

*/

public static int lastIndexOf(byte[] org, byte[] search) {

return lastIndexOf(org, search, 0);

}

/**

* 查找指定数组的最后一次出现起始索引

*

* @param org of type byte[] 原数组

* @param search of type byte[] 要查找的数组

* @param fromIndex 起始索引

* @return int 返回索引

*/

public static int lastIndexOf(byte[] org, byte[] search, int fromIndex) {

KMPMatcher kmpMatcher = new com.taobao.sketch.util.ArrayUtil.KMPMatcher();

kmpMatcher.computeFailure4Byte(search);

return kmpMatcher.lastIndexOf(org, fromIndex);

}

/**

* KMP算法类

*

* Created on 2011-1-3

*/

static class KMPMatcher {

private int[] failure;

private int matchPoint;

private byte[] bytePattern;

/**

* Method indexOf …

*

* @param text of type byte[]

* @param startIndex of type int

* @return int

*/

public int indexOf(byte[] text, int startIndex) {

int j = 0;

if (text.length == 0 || startIndex > text.length) return -1;

for (int i = startIndex; i < text.length; i++) {

while (j > 0 && bytePattern[j] != text[i]) {

j = failure[j - 1];

}

if (bytePattern[j] == text[i]) {

j++;

}

if (j == bytePattern.length) {

matchPoint = i – bytePattern.length + 1;

return matchPoint;

}

}

return -1;

}

/**

* 找到末尾后重头开始找

*

* @param text of type byte[]

* @param startIndex of type int

* @return int

*/

public int lastIndexOf(byte[] text, int startIndex) {

matchPoint = -1;

int j = 0;

if (text.length == 0 || startIndex > text.length) return -1;

int end = text.length;

for (int i = startIndex; i < end; i++) {

while (j > 0 && bytePattern[j] != text[i]) {

j = failure[j - 1];

}

if (bytePattern[j] == text[i]) {

j++;

}

if (j == bytePattern.length) {

matchPoint = i – bytePattern.length + 1;

if ((text.length – i) > bytePattern.length) {

j = 0;

continue;

}

return matchPoint;

}

//如果从中间某个位置找,找到末尾没找到后,再重头开始找

if (startIndex != 0 && i + 1 == end) {

end = startIndex;

i = -1;

startIndex = 0;

}

}

return matchPoint;

}

/**

* 找到末尾后不会重头开始找

*

* @param text of type byte[]

* @param startIndex of type int

* @return int

*/

public int lastIndexOfWithNoLoop(byte[] text, int startIndex) {

matchPoint = -1;

int j = 0;

if (text.length == 0 || startIndex > text.length) return -1;

for (int i = startIndex; i < text.length; i++) {

while (j > 0 && bytePattern[j] != text[i]) {

j = failure[j - 1];

}

if (bytePattern[j] == text[i]) {

j++;

}

if (j == bytePattern.length) {

matchPoint = i – bytePattern.length + 1;

if ((text.length – i) > bytePattern.length) {

j = 0;

continue;

}

return matchPoint;

}

}

return matchPoint;

}

/**

* Method computeFailure4Byte …

*

* @param patternStr of type byte[]

*/

public void computeFailure4Byte(byte[] patternStr) {

bytePattern = patternStr;

int j = 0;

int len = bytePattern.length;

failure = new int[len];

for (int i = 1; i < len; i++) {

while (j > 0 && bytePattern[j] != bytePattern[i]) {

j = failure[j - 1];

}

if (bytePattern[j] == bytePattern[i]) {

j++;

}

failure[i] = j;

}

}

}

public static void main(String[] args) {

try {

byte[] org = “kadeadedcfdededghkk”.getBytes(“GBK”);

byte[] search = “kk”.getBytes(“GBK”);

int last = lastIndexOf(org, search, 19);

long t1 = 0;

long t2 = 0;

int f1 = 0;

int f2 = 0;

for (int i = 0; i < 10000; i++) {

long s1 = System.nanoTime();

f1 = indexOf(org, search, 0);

long s2 = System.nanoTime();

f2 = com.alibaba.common.lang.ArrayUtil.indexOf(org, search);

long s3 = System.nanoTime();

t1 = t1 + (s2 – s1);

t2 = t2 + (s3 – s2);

}

System.out.println(“kmp=” + t1 / 10000 + “,ali=” + t2 / 10000);

System.out.printf(“f1=” + f1 + “,f2=” + f2);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

}

.net

在 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

{

///

/// stream 、 string 、byte[] 间的转换扩展方法类

///

public static class StreamExtend

{

#region Stream 扩展

///

/// Stream Stream 转换为 byte 数组

///

///

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;

}

///

/// Stream 转换为 image 图片

///

///

public static Image ToImage(this Stream stream)

{

Image img = new Bitmap(stream);

return img;

}

///

/// Stream 转换为 string ,使用 Encoding.Default 编码

///

///

public static string ToStr(this Stream stream)

{

return System.Text.Encoding.Default.GetString(stream.ToByteArray());

}

///

/// 在当前流中搜索指定的 byte[]

///

///

/// 搜索关键字

/// 搜索开始位置

/// 如果存在则返回byte[]在流中首次出现的位置,否则返回 -1

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

{

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[] 扩展

///

/// byte[] 转换为 stream 流

///

///

public static Stream ToStream(this byte[] arr)

{

Stream stream = new MemoryStream(arr);

// 设置当前流的位置为流的开始 www.2cto.com

stream.Seek(0, SeekOrigin.Begin);

return stream;

}

///

/// byte[] 转换为 Image

///

///

public static Image ToImage(this byte[] arr)

{

return Image.FromStream(arr.ToStream());

}

///

/// 转换为 string,使用 Encoding.Default 编码

///

///

public static string ToStr(this byte[] arr)

{

return System.Text.Encoding.Default.GetString(arr);

}

///

/// 搜索

///

///

/// 搜索关键字

/// 搜索开始位置

///

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 扩展

///

/// string 转换为 byte[]

///

///

public static byte[] ToByteArray(this string str)

{

return System.Text.Encoding.Default.GetBytes(str);

}

///

/// string 转换为 Stream

///

///

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);

java byte数组操作_Byte数组操作方法集(Java.Net)相关推荐

  1. java byte转成int数组_Java任意长度byte数组转换为int数组的方法

    前言 嗯.最近工程上遇到一个byte数组转换为int的问题,解决过程中遇到了几个坑,经过各种查资料终于还是解决了.撒花. Java的位运算以及byte数组与其他类型数据的转换比c/c++感觉麻烦一些. ...

  2. python3-numpy 数组操作--修改数组形状、翻转数组、修改数组维度、连接数组、分割数组、数组元素的添加与删除

    1.修改数组形状 函数 描述 reshape 不改变数据的条件下修改形状 flat 数组元素迭代器 flatten 返回一份数组拷贝,对拷贝所做的修改不会影响原始数组 ravel 返回展开数组 1.1 ...

  3. PHP数组操作——获取数组最后一个值的方法

    来源:http://www.jb51.net/article/64097.htm php开发过程中,可能经常需要对取出的数组要获取数组的最后健或值.在这里脚本之家总结了三个方法,并且跟据他们三个方法在 ...

  4. JavaScript对JSON数组操作。数组添加(push)以及移除(splitce)

    这里写一个小栗子提供给大家学习和纪录.  js声明数组 以及向数组中添加as移除json数据 JavaScript声明JSON数组的方法: //部分条件,在数据渲上数据要求是数组格式而非json数组格 ...

  5. java byte 判断相等_你真的了解Java中quot;==quot;和equals()的区别?

    部分面试资料链接:https://pan.baidu.com/s/1qDb2YoCopCHoQXH15jiLhA 密码:jsam 想获得全部面试必看资料,关注公众号,大家可以在公众号后台回复" ...

  6. java 16进制数组 字符串_byte数组转换成16进制字符串和字符数组的方法

    byte数组转换成16进制字符串String: public class CommonUtil { /** * byte数组转换成16进制字符串 * @param src * @return */ p ...

  7. mysql 存byte数组中_byte数组存储到mysql

    public int AddVeinMessage(byte[] data)//插入数据库 { using (BCSSqlConnection = new MySqlConnection(strCon ...

  8. Scala编程入门---数组操作之数组转换

    使用yield和函数式编程转换数组 //对Array进行转换,获取的还是Aarry val a = Array(1,2,3,4,5) val a2 = for(ele <- a) yield e ...

  9. 数组操作-删除数组中指定元素

    删除数组中指定元素 //删除数组中指定元素removeByValue(arr, val) {for (var i = 0; i < arr.length; i++) {if (arr[i] == ...

最新文章

  1. mysql left join 慢 的一个原因
  2. qt opencv库配置大全
  3. 【Android 逆向】APK 文件格式 ( Android 应用安装 | Zip 文件格式 | 使用 Python 代码提取 APK 文件 )
  4. sai u 2016
  5. moss自定义内容查询webpart
  6. GNN论文笔记: Graph Neural Networks with convolutional ARMA filters
  7. 【我的区块链之路】- Hyperledger fabric的简单入门(四)链码的编写及调试
  8. Ladda – 把加载提示效果集成到按钮中,提升用户体验
  9. VUE3 项目自定义修改网页标题和图标
  10. 为 IDES471 激活中文
  11. 这可能是你见过的最全的网络爬虫总结
  12. linux保密检查工具,linux使用lynis检查系统安全
  13. spss 因子分析非正定矩阵解决方案
  14. 修改硬盘固件的木马 探索方程式(EQUATION)组织的攻击组件
  15. Linux内核学习1——Linux内核编译安装
  16. n−皇后问题 (dfs)
  17. 方舟生存进化服务器存档位置,方舟生存进化如何转移存档
  18. QQ公众号微信公众号,左右互搏?
  19. NO.003-2018.02.08《江城子·乙卯正月二十日夜记梦》宋代:苏轼
  20. WIN10插上耳机还是声音外放

热门文章

  1. Elasticsearch:如何在 Elasticsearch 中正确使用同义词功能
  2. 解决 Moveit中error: Trajectory message contains waypoints that are not strictly increasing in time
  3. 2019 vs 安装odt_北京市2019二级造价师考试教材出版信息,免费送考试大纲
  4. 复习Java第二个项目仿QQ聊天系统 03(两种通信类、登录以及注册功能完善) Java面试题并发编程相关知识生活【记录一个咸鱼大学生三个月的奋进生活】025
  5. 产品经理的一天应该怎么过
  6. 航盾打印系统服务器,航盾光盘刻录监控审计及管理系统 技术白皮书.pdf
  7. 相机java程序_构建相机应用程序 - 接收
  8. linux桌面环境哪个好,你应该选择哪一个Linux桌面环境?
  9. 不要和任何人熟得太快
  10. 聊聊知乎订单系统迁移