Search the data byte array for the first occurrence of the byte array pattern. - Java java.lang

Java examples for java.lang:byte Array

Description

Search the data byte array for the first occurrence of the byte array pattern.

Demo Code

/**// w  w  w .  ja va  2s  .  c  o  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        int length = 2;
        byte[] pattern = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(indexOf(data, offset, length, pattern));
    }

    /**
     * Search the data byte array for the first occurrence of the byte array
     * pattern.
     */
    public static final int indexOf(byte[] data, int offset, int length,
            byte[] pattern) {
        int[] failure = computeFailure(pattern);

        int j = 0;

        for (int i = 0; i < length; i++) {
            while (j > 0 && pattern[j] != data[offset + i]) {
                j = failure[j - 1];
            }
            if (pattern[j] == data[offset + i]) {
                j++;
            }
            if (j == pattern.length) {
                return offset + (i - pattern.length + 1);
            }
        }
        return -1;
    }

    /**
     * Computes the failure function using a boot-strapping process, where the
     * pattern is matched against itself.
     */
    private static final int[] computeFailure(byte[] pattern) {
        int[] failure = new int[pattern.length];

        int j = 0;
        for (int i = 1; i < pattern.length; i++) {
            while (j > 0 && pattern[j] != pattern[i]) {
                j = failure[j - 1];
            }
            if (pattern[j] == pattern[i]) {
                j++;
            }
            failure[i] = j;
        }

        return failure;
    }
}

Related Tutorials