Java Reference
In-Depth Information
Lines 19-24 use method
lastIndexOf
to locate the last occurrence of a character in a
String
. The method searches from the end of the
String
toward the beginning. If it finds
the character, it returns the character's index in the
String
—otherwise, it returns -1.
There are two versions of
lastIndexOf
that search for characters in a
String
. The expres-
sion at line 20 uses the version that takes the integer representation of the character. The
expression at line 22 uses the version that takes two integer arguments—the integer repre-
sentation of the character and the index from which to begin searching
backward
.
Lines 27-40 demonstrate versions of methods
indexOf
and
lastIndexOf
that each
take a
String
as the first argument. These versions perform identically to those described
earlier except that they search for sequences of characters (or substrings) that are specified
by their
String
arguments. If the substring is found, these methods return the index in
the
String
of the first character in the substring.
Class
String
provides two
substring
methods to enable a new
String
object to be creat-
ed by copying part of an existing
String
object. Each method returns a new
String
object.
Both methods are demonstrated in Fig. 14.6.
1
// Fig. 14.6: SubString.java
2
// String class substring methods.
3
4
public class
SubString
5
{
6
public static void
main(String[] args)
7
{
8
String letters =
"abcdefghijklmabcdefghijklm"
;
9
10
// test substring methods
11
System.out.printf(
"Substring from index 20 to end is \"%s\"%n"
,
12
letters.substring(
20
)
);
13
System.out.printf(
"%s \"%s\"%n"
,
14
"Substring from index 3 up to, but not including 6 is"
,
15
letters.substring(
3
,
6
)
);
16
}
17
}
// end class SubString
Substring from index 20 to end is "hijklm"
Substring from index 3 up to, but not including 6 is "def"
Fig. 14.6
|
String
class
substring
methods.
The expression
letters.substring(20)
at line 12 uses the
substring
method that
takes one integer argument. The argument specifies the starting index in the original
String
letters
from which characters are to be copied. The substring returned contains
a copy of the characters from the starting index to the end of the
String
. Specifying an
index outside the bounds of the
String
causes a
StringIndexOutOfBoundsException
.
Line 15 uses the
substring
method that takes two integer arguments—the starting
index from which to copy characters in the original
String
and the index one beyond the