Java ArrayList Search search(ArrayList src, ArrayList pattern, int start)

Here you can find the source of search(ArrayList src, ArrayList pattern, int start)

Description

Searches an ArrayList of Strings starting from a specific position for a pattern

License

Open Source License

Parameter

Parameter Description
src the input ArrayList of Strings
pattern the pattern to search for
start the starting position

Return

the index of the first occurrence or -1 if no matches found

Declaration

public static int search(ArrayList<String> src,
        ArrayList<String> pattern, int start) 

Method Source Code

//package com.java2s;
/**//from   www . ja  v a2  s. c om
 * 
 * Copyright 1999-2012 Carnegie Mellon University.  
 * Portions Copyright 2002 Sun Microsystems, Inc.  
 * Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
 * All Rights Reserved.  Use is subject to license terms.
 * 
 * See the file "license.terms" for information on usage and
 * redistribution of this file, and for a DISCLAIMER OF ALL 
 * WARRANTIES.
 *
 */

import java.util.ArrayList;

public class Main {
    /**
     * Searches an ArrayList of Strings starting from a specific position for a
     * pattern
     * 
     * @param src the input ArrayList of Strings
     * @param pattern the pattern to search for
     * @param start the starting position
     * @return the index of the first occurrence or -1 if no matches found
     */
    public static int search(ArrayList<String> src,
            ArrayList<String> pattern, int start) {
        int index = -1;
        int pos = -1;
        int startpos = 0;
        if (start > src.size() - pattern.size()) {
            return -1;
        }

        do {
            pos = src.subList(startpos + start,
                    src.size() - pattern.size() + 1)
                    .indexOf(pattern.get(0));
            if (pos == -1) {
                return pos;
            }

            boolean flag = true;
            for (int i = 1; i < pattern.size(); i++) {
                if (!src.get(startpos + start + pos + i).equals(
                        pattern.get(i))) {
                    index = -1;
                    flag = false;
                    break;
                }
            }

            if (flag) {
                index = startpos + pos;
                break;
            } else {
                startpos += pos + 1;
            }
        } while (startpos + start < src.size());

        return index;
    }
}

Related

  1. search(String token, ArrayList iniTokens)
  2. searchInElement(String name, Map> elementMap)
  3. searchString(String name, ArrayList input)