SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

Write a recursive method called indexOf that accepts two strings as parameters and that returns the starting index of the first occurrence of the second string inside the first string (or 1 if not found). For example, the call of indexOf("Barack Obama", "bam")would return 8. (Strings already have an indexOf method, but you may not call it in your solution.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package recursion;

public class StringIndex {

	public static int indexOf(String string1, String string2) {
        // check if string1 is less than string2
		if (string1.length() < string2.length())
			return -1;
        
        // check if substring of string1 equals string2
		boolean equals = string1.substring(0, string2.length()).equals(string2);
		if (equals)
			return 0;

        //take the substring starting from index 1 in the string1 variable
		string1 = string1.substring(1);
        // recursive call on index
		int index = indexOf(string1, string2);

		if (index == -1)
			return -1;

		return 1 + index;
	}

	public static void main(String[] args) {

		String string1 = "is there anybody here?";
		String string2 = "any";
		System.out.print("the string \""+string2+"\" repeats again in the string \""+string1+"\" at index: ");
		System.out.println(indexOf(string1, string2));
		

	}

}
Output:

the string "any" repeats again in the string "is there anybody here?" at index: 9

 

0 0

Discussions

Post the discussion to improve the above solution.