Java - Write code to Get the first index in a string that contains any of the char objects in characters.

Requirements

Write code to Get the first index in a string that contains any of the char objects in characters.

Demo

public class Main{
    public static void main(String[] argv){
        String str = "book2s.com";
        char[] characters = new char[]{'b','o','o','k','2','s','.','c','o','m','a','1',};
        System.out.println(indexOfAny(str,characters));
    }//  www. java  2 s . c o  m
    /***
     * Gets the first index in a string that contains any of the char objects in
     * characters.
     * 
     * @param str
     *            The string to search.
     * @param characters
     *            The characters to search for.
     * @return The index of first occurrence of any item in characters found in
     *         str.
     */
    public static int indexOfAny(final String str, final char[] characters) {
        return loopIndexOfAny(str, characters, 0, 1);
    }
    /***
     * Loops through the bounds of str starting at start and incrementally moves
     * in the direction of adder.<br>
     * <br>
     * 
     * The loop searches for a single character in the bounds of str that is in
     * the collection of characters.
     * 
     * @param str
     *            The string to search.
     * @param characters
     *            The characters to search for.
     * @param start
     *            The index to start searching.
     * @param adder
     *            The number of indices to jump when incrementing to the next
     *            character.
     * @return The index of the instance of any character in str. Returns less
     *         than 0 if nothing can be found.
     */
    private static int loopIndexOfAny(final String str,
            final char[] characters, final int start, final int adder) {
        for (int index = start; index >= 0 && index < str.length(); index += adder) {
            char c = str.charAt(index);

            if (ZArrayUtil.contains(characters, c)) {
                return index;
            }
        }
        return -1;
    }
}