* Write a recursive function that finds the index of s2 in s1. Do not use any * string functions except for .length(), .equals(), and .substring(). Do not use * any loops, or any data structures.

Respuesta :

Answer:

public int indexOfStrings(String s1, String s2) {

if(s1.length() < s2.length())

return -1;

if(s1.substring(0, s2.length()).equals(s2))

return 0;

int index = indexOf(s1.substring(1), s2);

if(index == -1)

return -1;

return 1 + index;

}

Explanation:

First create the method indexOfStrings to receive 2 strings s1 and s2.

Then test with an 'if' statement to check if the length of s1 is less than s2. We hope to find the index s2 in s1 therefore s1 should be greater in length than s2. If this doesn't follow them it should return -1 showing negativity in the function.

Then with check using a substring () function with the endIndex as the length of s2 and beginIndex as 0, to see if the new substring of s1 is equal to string s2. If this true we return 0 and the method ends.

We the initialize index as integer, and repeat the function and insert the substring of s1 with a beginIndex of 1, and the second variable as s2.

We test to see if this index will be equal to -1(negative), if true we end the function.

Finally if all goes well the method returns 1 plus the index integer.