/* Java application that includes solutions to the problems in Quiz #2 ** and whose main() method "exercises" those solutions on test data. ** ** Given was the specification of the posOfKth() method, with the ** instruction that it should be used. The task was to supply the ** bodies of the replace() and remove() methods. ** ** Programming Assignment #4 involved developing Java methods in a ** CSV_Utility class. Among these was setIthField(), which differs ** from replace() only in technical details. */ public class Quiz2_F25_Sol { public static void main(String[] args) { String s = "$The$cat$in$the$hat$ate$a$rat$"; String t = "GLORP"; for (int k=1; k != 10; k++) { System.out.printf("s: \"%s\"; k: %d; t: \"%s\"\n", s, k, t); System.out.printf("replace(s,k,t) yields \"%s\"\n", replace(s,k,t)); System.out.printf("remove(s,k) yields \"%s\"\n\n", remove(s,k)); } } /* Returns the position, within string s, of the k-th occurrence of ch. ** If there are fewer than k occurrences of ch within s, the value returned ** is s.length(). ** pre: k >= 1 && s != null */ public static int posOfKth(String s, char ch, int k) { int result; int j = 0; int count = 0; while (j != s.length() && count != k) { if (s.charAt(j) == ch) { count = count + 1; } j = j+1; } // assert: if count != k, then j == s.length() and there are // fewer than k occurrences of ch within s. Otherwise, // the k-th occurrence of ch is at position j-1. if (count == k) { j = j-1; } return j; } /* Returns the string resulting from replacing, by String t, the substring ** of s in between its k-th and (k+1)-st occurrences of '$'. If there are ** k or fewer occurrences of '$' within s, the string returned is s. ** pre: k >= 1 && s != null */ public static String replace(String s, int k, String t) { if (posOfKth(s, '$', k+1) == s.length()) { // s has k or fewer occurrences of '$', so return s return s; } else { // Find the positions within s of the k-th and (k+1)-st // occurrences of '$'. int posK = posOfKth(s, '$', k); int posKPlus1 = posOfKth(s, '$', k+1); // Obtain the prefix of s up to and including the k-th // occurrence of '$', and the suffix of s starting at the // (k+1)-st occurrence of '$'. String prefix = s.substring(0, posK + 1); String suffix = s.substring(posKPlus1); // Paste s back together again, but with t replacing the // substring in between the k-th and (k+1)-st occurrences of '$'. return prefix + t + suffix; } } /* Returns the string resulting from removing from s the characters ** in between its the k-th and (k+1)-st occurrences of '$'. If there ** are k or fewer occurrences of '$' within s, the string returned is s. ** pre: k >= 1 && s != null */ public static String remove(String s, int k) { // Observe that removing a substring is the same as replacing // that substring by the empty string. return replace(s, k, ""); } }