Recursively Search for String in Java
public static void main(String args)
Scanner s=new Scanner(System.in);
System.out.println("Enter main string");
System.out.println("Enter search string");
System.out.println("Found at index "+idx);
System.out.println("Totally found "+i+" times.");
Recursive String Search Output
Enter main stringthis is a sample test.Enter search stringisFound at index 2Found at index 5Totally found 2 times.
Explaining The Logic
idx=-1which indicates that the string is not found at first.
int i is for counting the no.of times the string occurred.
Loop till the end of the main string, the string in which the search has to go.
idx=st.indexOf(se,i+idx);which updates the value of idx with the index of the search string in the main string. i+idx is because when the loop updates, the next search has to start after the last index.
if(idx==-1)break;Exit the loop if the string is not found. Whenever the string is not found, the loop is terminated.
i is the value which is nothing but the no.of times the string had occurred in the main string. Because i value will be updated only with the no.of times the string is according to the logic.