logo Practice-It logo


Language/Type: Java recursion recursive programming
Author: Stuart Reges (on 2014/02/13)

Write a method indexOf that takes two Strings as parameters and that returns the starting index of the first occurrence of the second String inside the first String (-1 if not found). For example:

        indexOf("Barack Obama", "Bar") returns 0
        indexOf("Barack Obama", "ck") returns 4
        indexOf("Barack Obama", "a") returns 1
        indexOf("Barack Obama", "BAR") returns -1

Notice that case matters, as in the last example that returns -1 because the second String does not occur inside the first String.

The String class includes an indexOf method and you are not allowed to simply call it to solve this problem. You are limited to the following String methods:

        equals(other)                  Returns whether this String is equal to
                                       the other object
        length()                       Returns the length of the String
        substring(fromIndex, toIndex)  Returns a new string that is a substring
                                       of this string from startIndex
                                       (inclusive) to stopIndex (exclusive)
        substring(fromIndex)           Returns a new string that is a substring
                                       of this string from startIndex
                                       (inclusive) to the end of the String

For example, if a String s stores the text "hello", then:

        s.equals("hello") returns true
        s.length() returns 5
        s.substring(1, 3) returns "el"
        s.substring(2) returns "llo"

You are not allowed to construct any structured objects other than Strings (no array, StringBuilder, Scanner, etc) and you may not use a while loop, for loop or do/while loop to solve this problem; you must use recursion.

Type your solution here:

This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.