简体   繁体   中英

How to find the index of first occurence of any character from another string in a string?

/* returns the index of the first occurrence of any of the
 * characters in chars in String s or -1 if none of the characters
 * in chars are found in s. */

Above are the instructions, below is my code.

public static void main(String[] args){

     indexOfAny("kabomba","bomb");

}   

public static int indexOfAny(String s, String chars) {

        int index = 0;
        String rev = "";

        for(int i = s.length()-1;i>=0;i--){
            rev+=s.charAt(i);
        }

        String x = rev;

        for(int i = 0;i<x.length();i++){

            for(int j = 0; j<chars.length();j++){
                if(x.charAt(i)==chars.charAt(j)){
                    index = i;//**
                }else {
                    index = -1;
                }
            }
        }
        System.out.println(index);
        return index;
    }

To rephrase, the problem is at ** where the it will reach string x last character and compare if the characters in chars string are same and return -1, but I want the code to end and return the index of string x at the i after the last occurrence of any of characters from string chars in string x.

so the output should be 4. because the index of b, which is one of characters of string chars, in the reverse string is 4, which is what I want.

You can use StringUtils class which prevents to iterate the loop. Here are the indexOf methods present. OR

You can use String.indexOf method which is present under string class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM