/** 12/3/2018
  * substring
  * concat (same as +) s1+s2  s1.concat(s2)
  * trim
  * replace, replaceAll, split 
  we also discussed regular expressions, specifically use [ ] to hold a set
  of characters to match (both split and replaceAll accept a regular expresssion.*/

import java.util.Scanner;

public class MoreStringMethods {
  public static void main(String[] args) {
    String name = "John Doe";
    String first = name.substring(0,5);
    String last = name.substring(5);
    first = first.trim();
    System.out.println("first name is: " + first + " last name: " + last);
    // the above ex (John Doe) was trivial since we used a specific name
    // suppose I want to extract first and last name in general
    System.out.println("Enter first name followed by last name (separated with a space): ");
    Scanner sc = new Scanner(System.in);
    name = sc.nextLine(); // read in String with spaces
    int loc = name.indexOf(" ");
    System.out.println("loc is: " + loc);
    if (loc!=-1) {
       first = name.substring(0, loc);
       last = name.substring(loc+1);
       System.out.println("first name is: " + first + " last name: " + last);
    }
    // print the initials (assuming I have fullname in name)
    char firstInit = name.charAt(0);
    char lastInit = name.charAt(name.indexOf(" ")+1);
    System.out.println("Initials are:");
    System.out.println(firstInit + " " + lastInit);

    String sentence = "Today is Monday, next week is the last week of the semester.";
    int n=3; 
    // retreive the nth word from the sentence
    // Solution #1
    // find space n-1
    loc=-1;
    for (int i=0; i<n-1; i++) {
      loc = sentence.indexOf(" ",loc+1);
    }
    // fall out of the loop
    String word = sentence.substring(loc+1, sentence.indexOf(" ", loc+1));
    word = word.replaceAll("[.,]","");
    System.out.println(n + "th word  is: " + word);
    // Solution  #2
    // to remove all punctuation
    sentence = sentence.replaceAll("[,.?!:;]", ""); 
    String[] wordsArr = sentence.split(" "); // sentence.split("[\\s:]");
    for (int i=0; i<wordsArr.length; i++)
      System.out.println(wordsArr[i]);
    System.out.println(n + "th word  is: " + wordsArr[n-1]);
     
    String newSentence = sentence.replace(' ', '*');
    System.out.println("newSentence\n" + newSentence);
    System.out.println("sentence\n" + sentence);
    
    // cipher: remove punctuation and spaces. use a replacement alphabet
    char[] alphaBet = {'g', 'z', 'h', 'a'};
    char[] alphabet = {'a', 'b', 'c', 'd'};
    
    String msg = "abbabbcd";
    for (int i=0;i<alphabet.length;i++) {
        msg = msg.replace(alphabet[i], alphaBet[i]);
    }
    System.out.println(msg);
  }
}