Here is a classical implementation:
package javaforums;
public class StringCount
{
public static void main(String[] args)
{
String source = "String having a lot of instances of the substring in";
String query = "in";
int occ = 0;
int pos = source.indexOf(query);
while (pos != -1)
{
System.out.println("Query string [" + query + "] found at index: " + pos);
occ++;
pos = source.indexOf(query, pos + query.length());
}
System.out.println("Query string [" + query + "] found: " + occ + " times");
}
}
When you run it, it will display:
Query string [in] found at index: 3
Query string [in] found at index: 10
Query string [in] found at index: 23
Query string [in] found at index: 46
Query string [in] found at index: 50
Query string [in] found: 5 times
You can adapt it to your requirements so you read the source and query strings from the console. Enjoy.