import java.util.Scanner;
/** Matcher illustrates the following methods in the String class:
  * indexOf (note there are 4 overloaded versions of indexOf 
  * which essentially searches a string for either a character or a String
  */
public class Matcher {
  public static void main(String[] args) {
    String sentence = "I am looking for a needle in a haystack.";
    String pattern = "need";
    int loc = sentence.indexOf(pattern);
    System.out.println(pattern + " occurs at loc " + loc + " in " + sentence);
    char ch = 'a';
    loc = sentence.indexOf(ch, 10);
    System.out.println("a occurs in " + sentence + " at loc " + loc);
    loc = sentence.indexOf('c');
    System.out.println("c occurs in " + sentence + " at loc " + loc);
    
    // lets say I want to print all occurrences of say the char 'a'
    for (int i=0; i<sentence.length();i++)
        if (sentence.charAt(i)==ch)
            System.out.println(ch + " found at loc " + i);
    // using indexOf and while loop
    loc = sentence.indexOf(ch); // this will find the first char ch in sentence
    while(loc!=-1) {
      // find NEXT location
      System.out.println(ch + " found at loc " + loc);
      loc = sentence.indexOf(ch, loc+1);
    }
    
    String text = "finding substrings inininin strinings";
    pattern = "in";
    loc = text.indexOf(pattern); // this will find the first char ch in sentence
    while(loc!=-1) {
      // find NEXT location
      System.out.println(pattern + " found at loc " + loc);
      loc = text.indexOf(pattern, loc+1);
    }
    
    // given 2 Strings, text and a pattern, print whether the pattern
    // occurs in the text twice consecutively (i.e. in tandem)
    loc = text.indexOf(pattern);
    while (loc!=-1) {
          int loc2 = text.indexOf(pattern, loc+pattern.length());
          if (loc2 == pattern.length()+loc)
             System.out.println("tandem of " + pattern + " found!");
          loc = loc2;
    }
    // another way of solving it
    String twoPat = pattern+pattern;
    System.out.println(text.indexOf(twoPat));
    
    // lets say I wanted to implement the indexOf functionality myself
    // iterate through the sentence, try to match pattern at each location
    for (int i=0; i<=sentence.length()-pattern.length(); i++) {
      // compare pattern to substring of sentence beg at loc i
      // therefore we will loop through the characters of the pattern
      int count=0; 
      for (int j=0; j<pattern.length(); j++) {
        if (sentence.charAt(i+j) == pattern.charAt(j)) {
              count++;
        }
        if (count==pattern.length()) {
          System.out.println("We found it at loc: " + i);
        }
      } // end for j (loops through pattern)
      count=0; // for next iteration of i
    }  
    
     // to search non-case-sensitive
    pattern = pattern.toLowerCase();
    text.toLowerCase().indexOf(pattern);
  }
}


