Dates and Strings
StringBuilder class
Code
Code that creates a phone number
StringBuilder phoneNumber = new StringBuilder(); phoneNumber.append("977"); phoneNumber.append("555"); phoneNumber.append("1212"); Code that adds dashes to a phone number phoneNumber.insert(3, '-'); phoneNumber.insert(7, '-');
Code that removes dashes from a phone number
for(int i = 0; i < phoneNumber.length(); i++) { if (phoneNumber.charAt(i) == '-') phoneNumber.deleteCharAt(i--); }
Code that parses a phone number
StringBuilder phoneNumber = new StringBuilder("977-555-1212"); String areaCode = phoneNumber.substring(0,3); String prefix = phoneNumber.substring(4,7); String suffix = phoneNumber.substring(8);
Code that shows how capacity automatically increases
StringBuilder name = new StringBuilder(8); int capacity1 = name.capacity(); // capacity1 is 8 name.append("Raymond R. Thomas"); int length = name.length(); // length is 17 int capacity2 = name.capacity(); // capacity2 is 18 (2 * capacity1 + 2)