Returns the index within this string of the first occurrence of any of the characters specified in string any. - Java java.lang

Java examples for java.lang:String Index

Description

Returns the index within this string of the first occurrence of any of the characters specified in string any.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String string = "java2s.com";
        String any = "b";
        System.out.println(indexOfAny(string, any));
    }/*  w  ww .j ava  2s . co m*/

    /**
     * Returns the index within this string of the first occurrence of any of
     * the characters specified in string any. If none of the characters occur
     * in this string, then -1 is returned.
     * 
     * @param string
     *            the string to search
     * @param any
     *            the characters to search for
     * @return the first index of any of the characters in "any" in "string", or
     *         -1 if none are found.
     */
    public static int indexOfAny(String string, String any) {
        return indexOfAny(string, any, 0);
    }

    /**
     * Returns the index within string of the first occurrence of any of the
     * characters specified in any at or after the character at index start. If
     * none of the characters occur in the substring, then -1 is returned.
     * 
     * @param string
     *            the string to search
     * @param any
     *            the characters to search for
     * @param start
     *            the string index to start the search at
     * @return the first index of any of the characters in "any" in a substring
     *         of "string" from index start, or -1 if none are found.
     */
    public static int indexOfAny(String string, String any, int start) {

        if ((string == null) || (any == null)) {
            return -1;
        }
        try {
            int len = string.length();
            for (int i = start; i < len; i++) {
                if (any.indexOf(string.charAt(i)) >= 0) {
                    return i;
                }
            }
            return -1;
        } catch (StringIndexOutOfBoundsException e) {
            return -1;
        }
    }
}

Related Tutorials