Finding index of first substring I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?

Example:


  str = "happy" substr = "app"
  
  index = 1


My code:

public static int subStringIndex(String str, String substr) {
    int substrlen = substr.length();
    int strlen = str.length();
    int j = 0;
    int index = -1;

    if (substrlen &lt; 1) {
        return index;
    }
    else {
        for (int i = 0; i &lt; strlen; i++) {              // iterate through main string
            if (str.charAt(i) == substr.charAt(j)) {    // check substring
                index = i - j;                              // remember index
                j++;                                    // iterate
                if (j == substrlen) {                   // when to stop
                    return index;
                }
            }
            else {
                j = 0;
                index = -1;
            }
        }
    }
    return index;
}
Just checking that you intend to be reinventing-the-wheel, you can do:

System.out.println("happy".indexOf("app"));


You did know that, right?

Or, if you want to reformat the 'signature' to match yours, it is:

public static int subStringIndex(String str, String substr) {
    return str.indexOf(substr);
}


There are a number of helper methods on String which will help:


String.indexOf(substr) - return the index of the first occurrence of substr
String.indexOf(substr, start) - return the index of the first occurrence of substr on or after the start position.
String.lastIndexOf(substr) - return the index of the last occurrence of substr
String.lastIndexOf(substr, start) - return the index of the last occurrence of substr starting before the start position.
 -