查找数组是否包含另一个数组,不是查询元素

不是查询是否包含元素的.是查询是否严格包含的.工具类代码如下

public class ByteUtil {
	private static int indexOf(byte[] source, byte[] target) {

		return indexOf(source, target, 0);
	}

	private static int indexOf(byte[] source, byte[] target, int start) {
		// 获取来源和目标长度
		int sourceLen = source.length;
		int targetLen = target.length;
		if (sourceLen == 0 || targetLen == 0) {
			return -1;
		}
		if (sourceLen - start < targetLen) {
			return -1;
		}
		// 先在来源里面查找目标的首个字节.
		// 但是首个字节不必全查来源,
		// 来源减去目标的长度实际上也就是查询首个字节的最高偏移长度,如果超出此长度,首个字节即使相同,后面的长度不对也无法匹配.
		int offsetLen = sourceLen - targetLen + 1;// 偏移长度
		for (int i = start; i < offsetLen; i++) {
			if (source[i] != target[0]) {
				continue;// 筛查首个字节,直到匹配到
			}

			// 如果匹配到,那么再去检查相邻剩余字节,看是否能够匹配上.
			int end = 1;
			for (int j = i + 1; end < targetLen; j++) {
				byte b = source[j];
				byte c = target[end];

				if (b != c) {
					break;
				}
				end++;

			}
			;
			// 如果全都匹配上,那么必然end == targetLen,这时候返回i就行,否则继续外层循环重新查找首个字节.
			if (end == targetLen) {
				return i;
			}

		}

		return -1;
	}

	public static void main(String[] args) {

		byte[] aa = { 1, 2, 3, 3, 4, 5, 2, 3, 4, 5, 6 };
		byte[] bb = { 1, 2, 3, 3 };
		byte[] cc = { 2, 3, 3 };
		byte[] dd = { 3, 4, 5, 6 };
		byte[] ee = { 1, 2, 3, 3, 4, 5, 2, 3, 4, 5, 6 };
		byte[] ff = { 9 };
		byte[] gg = { 3, 4 };

		System.out.println(indexOf(aa, bb));// 0
		System.out.println(indexOf(aa, cc));// 1
		System.out.println(indexOf(aa, dd));// 7
		System.out.println(indexOf(aa, ee));// 0

		System.out.println(indexOf(aa, ff));// -1
		System.out.println(indexOf(aa, bb, 1));// -1
		System.out.println(indexOf(aa, cc, 1));// 1
		System.out.println(indexOf(aa, gg));// 3
		System.out.println(indexOf(aa, gg, 3));// 3
		System.out.println(indexOf(aa, gg, 4));// 7
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值