Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^128) | Arithmetic Expressions


The substring Method


The substringmethod returns a particular substring of a string. Assuming myStringis of type
String, a method call has the following form:

myString.substring(5, 20)

The arguments are integers that specify positions within the string. The method returns
the piece of the string that starts with the position specified by the first argument and con-
tinues to the position given by the second argument minus 1. Thus the length of the substring
returned by the example call is 20 5 = 15 characters. Note that substringdoesn’t change
myString; instead, it returns a new Stringvalue that is a copy of a portion of the string. The
following examples assume that the statement

myString = "Programming and Problem Solving";

has been executed:

Method Call String Contained in Value Returned by Method
myString.substring( 0 ,7) "Program"
myString.substring( 7 ,15) "ming and"
myString.substring(10, 10) ""
myString.substring(24, 31) "Solving"
myString.substring(24, 25) "S"

In the third example, specifying the second argument to be the same as the first produces
the empty string as the result. The last example illustrates how to obtain a single character
from a given position in the string.
If either of the arguments specifies a position beyond the end of the string, or if the sec-
ond argument is smaller than the first, then the call to substringresults in an error message.
One way to avoid such errors is to write the call to substringin the following form. Here,start
is an intvariable containing the starting position, and lenis another intvariable contain-
ing the length of the desired substring.

myString.substring(start, Math.min(start+len, myString.length()))

Recall from our discussion of Java’s math methods that Math.minreturns the smaller of
its two arguments. If, by accident,start+lenis greater than the length of the string, then min
returns the length of myStringinstead. In this way, we ensure that the second argument in
the call to substringcan be no greater than the length of myString. We assume that startis
less than the length of the string, but we can use the same sort of formula as the first argu-
ment if we aren’t certain that this assumption is valid.
Free download pdf