/* Let's practice with Strings and built-in String functions provided * in the java.lang.String library. */ public class StringFun { public static void main(String [] args) { // Create strings. String s1 = "dog"; String s2 = "house"; System.out.println (s2); // Output: ________________________ // Let's investigate charAt(). char c = s2.charAt(2); System.out.println(c); // Output: ________________________ // Comparing 2 strings. String s3 = new String("Dog"); boolean areEqual = s1.equals(s3); System.out.println(areEqual); // Output: ________________________ areEqual = s1.equalsIgnoreCase(s3); System.out.println(areEqual); // Output: ________________________ boolean isLessThan = s1.compareTo(s2) < 0; System.out.println(isLessThan); // Output: ________________________ // startsWith() and endsWith() are analogous. String s4 = new String("Happy"); boolean begin = s4.startsWith("ha"); System.out.println(begin); // Output: ________________________ boolean isAdverb = s4.endsWith("ly"); System.out.println(isAdverb); // Output: ________________________ System.out.println(s4.length()); // Output: ________________________ int locationT = s4.indexOf('t'); System.out.println(locationT); // Output: ________________________ // Some searching functions: indexOf(), lastIndexOf() and substring() String s5 = new String("Down came a jumbuck to drink beside" + " the billabong"); System.out.println(s5.length()); // Output: ________________________ System.out.println(s5.substring(5,9)); // Output: ____________________ int firstE = s5.indexOf('e'); int lastE = s5.lastIndexOf('e'); System.out.println(firstE); // Output: ________________________ System.out.println(lastE); // Output: ________________________ // Note that replace() doesn't change the receiver object. String s6 = s2.replace('h', 'm'); System.out.println(s2 + s6); // Output: ________________________ // Let's put strings together using the + operator. s1 = "dog"; s2 = "house"; s3 = s1 + 8 + s2; System.out.println(s3); // Output: ________________________ s5 = s5.replace('a','A').replace('e','E'); System.out.println(s5); // Describe what s5 looks like now. // "Tokenize" when we know the exact location of tokens. String s7 = String.format("%-20s %6d %4.2f", "Caine Mutiny", 179325, 7.8); String title = s7.substring(0, 20); int frames = Integer.parseInt(s7.substring(21, 27).trim()); double score = Double.parseDouble(s7.substring(28, 32).trim()); System.out.printf("%s\n", s7); // Output: ________________________ System.out.printf("%s\n", title); // Output: ________________________ System.out.printf("%d\n", frames); // Output: ________________________ System.out.printf("%4.2f\n", score);// Output: ________________________ } }