We write a program segment that stores p in string answer but in the form “first-
name last-name”, with the first letter of each name capitalized and the other let-
ters small. For example, execution of the program segment with each of these
inputs would produce
We start by writing code that extracts the first and last names from p . This
can be done in the three steps shown below. Each step uses English or our non-
Java notation because that is the simplest way to express it.
int i= index of the comma in p;
String lastName= p[0..i - 1];
String firstName= p[i + 2..];
The last two statements can be written in Java using function substring .
The first is more problematic. We could write a loop to search character by char-
acter for the comma, but class String contains a function indexOf that makes
the task simpler. A call p.indexOf(str) yields the first index in p of string str .
Therefore, we can write this sequence as:
int i= p.indexOf(",");
String lastName= p.substring(0,i);
String firstName= p.substring(i + 2);
We can use functions toUpperCase and toLowerCase of class String to
make sure that the first letters of the names are upper case and the rest lower case.
Thus, the final string answer is created using this assignment:
answer= firstName.substring(0,1).toUpperCase() +
" " +
The moral of this story is: become familiar with the methods of class
String , for their use may save you time and energy in dealing with strings.
Extracting an integer from a string
Suppose a string p contains a sequence of integers, separated by blanks. There
may be blanks at the beginning and end of p as well. Here is an example of p :