HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Finding index of first substring

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
indexfirstsubstringfinding

Problem

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 < 1) {
        return index;
    }
    else {
        for (int i = 0; i < 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;
}

Solution

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.


-

Code Snippets

System.out.println("happy".indexOf("app"));
public static int subStringIndex(String str, String substr) {
    return str.indexOf(substr);
}

Context

StackExchange Code Review Q#38870, answer score: 7

Revisions (0)

No revisions yet.