// Arup Guha
// 7/14/03
// This is a short example to illustrate the use of the substring method
// in the string class. The program asks the user to enter a string and
// also a particular substring to search for within the first string.
// The program will print out the starting index of every matching
// substring.

// Edited on 7/8/2010 to use Scanner

import java.util.*;

public class SubString {

  	public static void main(String[] args) {

    	Scanner stdin = new Scanner(System.in);

    	// Get user input.
    	String text, pattern;
    	System.out.println("Enter a string.");
    	text = stdin.next();
    	System.out.println("Enter the substring to search for.");
    	pattern = stdin.next();
		
		/*** Old version of the program had this in main here:

		int count = 0;
    	// Search for string at each possible starting index.
    	for (int i=0; i<=text.length() - pattern.length(); i++) {

      		// Check the individual substring in question for equality.
      		if ( (text.substring(i,i+pattern.length())).equals(pattern) ) {
				System.out.println("There was a match starting at index "+i);
				count++;
      		} 
    	}	
		***/
		
		// Get the number of matches.
		int count = numMatches(text, pattern);

    	// Print out a message for both cases.
    	if (count > 0)
			System.out.println("There were "+count+" matches.");
		else
      		System.out.println("Sorry, there are no matches.");
		
		// Test method overloading of numMatches method.
		int numEs = numMatches(text, 'e');
		System.out.println("There were "+numEs+" lowercase es in your text.");
  	}
	
	// Returns the number of times pattern appears in text, possibly overlapping.
	public static int numMatches(String text, String pattern) {
		
		int result = 0;
    	// Search for string at each possible starting index.
    	for (int i=0; i<=text.length() - pattern.length(); i++) {

      		// Check the individual substring in question for equality.
      		if ( (text.substring(i,i+pattern.length())).equals(pattern) ) {
        		result++;
      		} 
    	}		
		
		return result;
	}
	
	// Returns the number of times c appears in text.
	public static int numMatches(String text, char c) {
		
		int result = 0;
		
		// Go through each letter, adding 1 to result for each match.
		for (int i=0; i<text.length(); i++)
			if (text.charAt(i) == c)
				result++;
		
		// Ta da!
		return result;
	}
}
