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

Requirements

Write code to Get the last 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(lastIndexOfAny(str,characters));
    }//  w w w .  j  a  v  a  2  s .c  o m
    /***
     * Gets the last 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 last occurrence of any item in characters found in
     *         str.
     */
    public static int lastIndexOfAny(final String str,
            final char[] characters) {
        return loopIndexOfAny(str, characters, str.length() - 1, -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;
    }
}