Recursively Search for String in Java

Recursively searching a string in Java
Illustrating searching string recursively in Java and getting it's indexes & also no.of times the string occurred.  This logic is easy and simple. Here is an example program.






import java.util.*;
class RecursiveStringSearch
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter main string");
String st=s.nextLine();
System.out.println("Enter search string");
String se=s.nextLine();
int idx=-1;
int i;
for(i=0;i<st.length();i++)
{
idx=st.indexOf(se,i+idx);
if(idx==-1)break;
System.out.println("Found at index "+idx);
}
System.out.println("Totally found "+i+" times.");
}
}


Recursive String Search Output


Enter main string
this is a sample test.
Enter search string
is
Found at index 2
Found at index 5
Totally found 2 times.

Explaining The Logic

Make the idx=-1 which 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.

No comments: