package test1; /** * A utility class for working with strings. * */ public class StringUtil { private StringUtil() { } /** * The version of this test. */ public static final String TEST_VERSION = "C"; /** * Returns the string formed by concatenating the argument * strings s and t with a separator string between them. * For example: * *
	 * Utility2B.join("abc", "xyz", ":")
	 * 
* * returns the string "abc:xyz". * * @param s a non-null string * @param t a non-null string * @param sep a non-null separator string * @return the string formed by concatenating s followed by * sep followed by t */ public static String join(String s, String t, String sep) { return s + sep + t; } /** * Returns the shortest of the two strings s and t. For example, * shortest("python", "java") returns the string * "java" because the string "java" is shorter * than the string "python". * * @param s a non-null string * @param t a non-null string * @return the shortest of the two strings s and t * @throws IllegalArgumentException if s and t have the same length */ public static String shortest(String s, String t) { if (s.length() == t.length()) { throw new IllegalArgumentException(); } if (s.length() < t.length()) { return s; } return t; } /** * Computes the number of characters that are different in * two strings of equal length. The strings are compared * character by character and the number of characters that * differ is returned. For example: * *
	 * distance("talk", "talk")    returns  0
	 * distance("talk", "walk")    returns  1
	 * distance("well", "walk")    returns  2    
	 * distance("pick", "walk")    returns  3
	 * distance("zzzz", "walk")    returns  4
	 * 
* * @param s a non-null string * @param t a non-null string * @return the number of characters that differ between s and t * @pre. s.length() == t.length() */ public static int distance(String s, String t) { int d = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != t.charAt(i)) { d++; } } return d; } /** * Returns the character that appears most frequently in the * string s. You may assume that only one character appears most * frequently in s. * * @param s a string * @return the character that appears most frequently in the * string s * @pre. s.length() is at least 1 */ public static char mostFrequentChar(String s) { int max = 1; char cmax = s.charAt(0); for (int i = 0; i < s.length(); i++) { int ct = 0; char ci = s.charAt(i); for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == ci) { ct++; } } if (ct > max) { max = ct; cmax = ci; } } return cmax; } }