Java tutorial
//package com.java2s; /* Copyright (c) 2010 Xiaoyun Zhu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.nio.ByteBuffer; public class Main { public final static int countP(final ByteBuffer bb, final byte[] text) { final int endIdx = bb.limit(); final byte[] array = bb.array(); return count(array, bb.position(), endIdx, text, 0, text.length); } public final static int countP(final ByteBuffer bb1, final ByteBuffer bb2) { final int end1 = bb1.limit(); final int end2 = bb2.limit(); final int offset1 = bb1.position(); final int offset2 = bb2.position(); final byte[] array1 = bb1.array(); final byte[] array2 = bb2.array(); return count(array1, offset1, end1, array2, offset2, end2); } public final static int count(final byte[] array1, final int offset1, final int end1, final byte[] array2) { return count(array1, offset1, end1, array2, 0, array2.length); } public final static int count(final byte[] array1, final int offset1, final int end1, final byte[] array2, final int offset2, final int end2) { final int len1 = end1 - offset1; final int len2 = end2 - offset2; int count = 0; if (len2 > 0 && len1 >= len2) { byte b; int idx = offset2; for (int i = offset1; i < end1; i++) { b = array1[i]; if (b == array2[idx]) { if (++idx >= end2) { count++; idx = offset2; } } else { idx = offset2; } } } return count; } public final static int count(final ByteBuffer bb, final byte[] text) { final int endIdx = bb.limit(); final byte[] array = bb.array(); return count(array, 0, endIdx, text, 0, text.length); } public final static int count(final ByteBuffer bb1, final ByteBuffer bb2) { final int end1 = bb1.limit(); final int end2 = bb2.limit(); final byte[] array1 = bb1.array(); final byte[] array2 = bb2.array(); return count(array1, 0, end1, array2, 0, end2); } }