Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;
}
share|improve this question
    
You can simplify that a great deal by not reassigning index at each step –  megawac Jan 9 at 2:14

2 Answers 2

up vote 2 down vote accepted

You can get away without the index variable as you're reassigning it at each step of your loop anyway.

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

    if (substrlen >= 1) {
        for (int i = 0; i < strlen; i++) {              // iterate through main string
            if (str.charAt(i) == substr.charAt(j)) {    // check substring
                j++;                                    // iterate
                if (j == substrlen) {                   // when to stop
                    return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen
                }
            }
            else {
                j = 0;
            }
        }
    }
    return -1;
}
share|improve this answer
    
Thanks! did not see this! much appreciated! –  Liondancer Jan 9 at 3:31

Just checking that you intend to be , 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:

share|improve this answer
    
I know there is a built in function but I wanted to solve the problem without it but thanks! –  Liondancer Jan 9 at 3:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.