Search char index Of Any in a String - Java java.lang

Java examples for java.lang:String Index

Description

Search char index Of Any in a String

Demo Code


public class Main{
    public static void main(String[] argv){
        String string = "java2s.com";
        char[] anyOf = new char[]{'b','o','o','k','2','s','.','c','o','m','','1',};
        System.out.println(indexOfAny(string,anyOf));
    }/*from w w w .j a v  a2s .  c o  m*/
    public static int indexOfAny(String string, char[] anyOf) {
        int lowestIndex = -1;
        for (char c : anyOf) {
            int index = string.indexOf(c);
            if (index > -1) {
                if (lowestIndex == -1 || index < lowestIndex) {
                    lowestIndex = index;

                    if (index == 0)
                        break;
                }
            }
        }

        return lowestIndex;
    }
    public static int indexOfAny(String string, char[] anyOf, int startIndex) {
        int indexInSubstring = indexOfAny(string.substring(startIndex),
                anyOf);
        if (indexInSubstring == -1)
            return -1;
        else
            return indexInSubstring + startIndex;
    }
    public static int indexOfAny(String string, char[] anyOf,
            int startIndex, int count) {
        int endIndex = startIndex + count;
        int indexInSubstring = indexOfAny(
                string.substring(startIndex, endIndex), anyOf);
        if (indexInSubstring == -1)
            return -1;
        else
            return indexInSubstring + startIndex;
    }
}

Related Tutorials