/* CST8110 - Introduction to Computer Programming
 * Section: 800
 * Semester: 20W
 * Professor: Piyush Jangam
 * Student ID: 040750891
 * Student Email: ross0272@algonquinlive.com
 * Lab 4
 */

public class CodingBatStrings {
    //Returns the string, minus any single char found between 'z' and 'p'
    public String zipZap(String str) {
        //Both lower case
        String newString = str.replaceAll("z.p", "zp");
        //Both upper case
        newString = newString.replaceAll("Z.P", "ZP");
        //Upper case 'Z', lower case 'p'
        newString = newString.replaceAll("Z.p", "Zp");
        //Lower case 'z', upper case 'P'
        newString = newString.replaceAll("z.P", "zP");
        
        return newString;
    }

    //Removes stars along with 1 char to right and left (if they exist)
    public String starOut(String str) {
        /* .? to allow 0 or 1 character, in case of beginning of line, using greedy quantifier
        *  [*]+ for 1 or more asterisks
        *  .? to allow 0 or 1 character, in case of end of line, using greedy quantifier
        *  Replaces the sequence with an empty string, effectively removing the sequence
        */
        String newString = str.replaceAll(".?[*]+.?", "");
        return newString;
    }

    //Count the number of words ending in 'y' or 'z', case insensitive
    public int countYZ(String str) {
        /* Max number of words is length of string divided by 2 (rounded up)
         * Since int division rounds down by default, 1 is added to compensate just in case
         * This also prevents an array length of less than 1
         */
        int maxWords = (str.length() / 2) + 1;
        //Create a blank array of words using the calculated max number of words
        String[] words = new String[maxWords];
        //Populate the array with words from str, delimited by non-letter characters
        words = str.split("[^a-zA-Z]");
  
        int numYZ = 0; //The tally of words ending in 'y' or 'z'
        for(int i = 0; i < words.length; i++) {
            //Don't bother checking empty Strings, otherwise an error can occur
            if (words[i].isEmpty()) {
                continue;
            }

            //Get the last character of the current word, this line is for readability
            char lastChar = words[i].charAt(words[i].length() - 1);
    
            //Check lower case options first
            if (lastChar == 'y' || lastChar == 'z') {
                //if the last character is 'y' or 'z', increment numYZ
                numYZ++;
            }
    
            //Check upper case options next
            if (lastChar == 'Y' || lastChar == 'Z') {
                //if the last character is 'Y' or 'Z', increment numYZ
                numYZ++;
            }
        }
        return numYZ;
    }
}