Dates and Strings
String class
Code
Code that parses a first name from a name string
String fullName = " Pamela Caldwell "; fullName = fullName.trim(); int indexOfSpace = fullName.indexOf(" "); String firstName = fullName.substring(0, indexOfSpace);
Code that parses a string containing a tab-delimited address
String address = "805 Main Street\tDallas\tTX\t12345"; address = address.trim(); String[] addressParts = address.split("\t"); String street = addressParts[0]; String city = addressParts[1]; String state = addressParts[2]; String zip = addressParts[3];
Code that adds dashes to a phone number
String phoneNumber1 = "9775551212"; String phoneNumber2 = phoneNumber1.substring(0, 3); phoneNumber2 += "-"; phoneNumber2 += phoneNumber1.substring(3, 6); phoneNumber2 += "-"; phoneNumber2 += phoneNumber1.substring(6); Code that removes dashes from a phone number String phoneNumber3 = "977-555-1212"; String phoneNumber4 = ""; for(int i = 0; i < phoneNumber3.length(); i++) { if (phoneNumber1.charAt(i) != '-') phoneNumber4 += phoneNumber3.charAt(i); }
Code that compares strings
String lastName1 = "Smith"; String lastName2 = "Lee"; int sortResult = lastName1.compareToIgnoreCase(lastName2); if (sortResult < 0) System.out.println(lastName1 + " comes first."); else if (sortResult == 0) System.out.println("The names are the same."); else System.out.println(lastName2 + " comes first.");
String customerNumber = ""; //if (customerNumber.equals("")) // old way //if (customerNumber.length() == 0) // old way if (customerNumber.isEmpty()) // Java 1.6 and later System.out.println("customerNumber contains an empty string.");