Page 204 - Introduction to Programming with Java: A Problem Solving Approach
P. 204
170 Chapter 5 Using Pre-Built Methods
to the afterEndIndex-1 position, where beginIndex and afterEndIndex are the substring method’s two parameters.
2
The following code fragment processes a quote from Candide. In its candide.substring(8)
method call, candide is the calling object, and 8 is the beginIndex parameter value. As you might recall, string indices start at 0. So the 8 refers to candide’s ninth character, which is ‘c’. Thus, the first println
statement prints cultivate
method call. The 3 and 17 refer to candide’s fourth and eighteenth characters, which are ‘m’ and a space. Thus, the second println statement prints must cultivate.
String candide = "we must cultivate our garden";
System.out.println(candide.substring(8));
System.out.println(candide.substring(3,17));
Output:
cultivate our garden
must cultivate
If you want to test the above code fragment or any of the following String method code fragments, use Figure 5.9’s program as a template. More specifically, replace Figure 5.9’s main method body with the new code fragment. Then compile and run the resulting program.
Position Determination Apago PDF Enhancer
Note the one-parameter indexOf methods in Figure 5.8. They return the position of the first occurrence of a given character or substring within the calling-object string. If the given character or substring does not appear within the calling-object string, indexOf returns 1.
Note the two-parameter indexOf methods in Figure 5.8. They return the position of the first occurrence of a given character or substring within the calling-object string, starting the search at the position specified by indexOf’s second parameter. If the given character or substring is not found, indexOf returns 1.
It’s common to use one of the indexOf methods to locate a character or substring of interest and then use one of the substring methods to extract it. For example, consider this code fragment:3
Here’s the beginning of the hamlet2 substring. String hamlet = "To be, or not to be: that is the question;";
int index = hamlet.indexOf(':');
String hamlet2 = hamlet.substring(index + 1);
System.out.println(hamlet2);
Output:
that is the question;
Notice that the first character printed is a space.
2 Voltaire, Candide, translated by Lowell Bair, Bantam Books, 1959, final sentence. 3 Shakespeare, Hamlet, Act III, Sc. 1.
our garden. Note the code fragment’s candide.substring(3,17)