/** * The methods in this class illustrate the use of Strings. * * @author Brad Richards * @version 1.0 */ public class StringExamples { /** * Takes a string like "Brad Richards" and returns just * the first name, "Brad". * * @param fullName A string representing the user's full name. * @return Just the user's first name. */ public String firstName(String fullName) { // Use indexOf to find the position of the space // Then use substring to chop off the right number of characters int indexOfSpace = fullName.indexOf(" "); if (indexOfSpace >= 0) { String firstName = fullName.substring(0,indexOfSpace); return firstName; } else { return fullName; } } public String firstName_shorter(String fullName) { return fullName.substring(0, fullName.indexOf(" ")); } /** * I want to take a name like "Bradley Eric Richards" and * just chop out and return the "Eric" part. * @param fullName A name that includes a middle name * @return Just the middle name */ public String middleName(String fullName) { // To Do: // Find position of first space int indexOfSpace = fullName.indexOf(" "); // Chop off everything up to and including first space String allButFirst = fullName.substring(indexOfSpace+1); // Look for the NEXT space indexOfSpace = allButFirst.indexOf(" "); // Chop off and return everything up to the next space String middle = allButFirst.substring(0,indexOfSpace); return middle; // For now... } public String middleName_shorter(String fullName) { // To Do: // Find position of first space int indexOfSpace = fullName.indexOf(" "); // Chop off everything up to and including first space String allButFirst = fullName.substring(indexOfSpace+1); return firstName(allButFirst); // For now... } }