Java Reference
In-Depth Information
18
// test lastIndexOf to find a character in a string
19
System.out.printf(
"Last 'c' is located at index %d%n"
,
20
letters.lastIndexOf(
'c'
)
);
21
System.out.printf(
"Last 'a' is located at index %d%n"
,
22
letters.lastIndexOf(
'a'
,
25
)
);
23
System.out.printf(
"Last '$' is located at index %d%n%n"
,
24
letters.lastIndexOf(
'$'
)
);
25
26
// test indexOf to locate a substring in a string
27
System.out.printf(
"\"def\" is located at index %d%n"
,
28
letters.indexOf(
"def"
)
);
29
System.out.printf(
"\"def\" is located at index %d%n"
,
30
letters.indexOf(
"def"
,
7
)
);
31
System.out.printf(
"\"hello\" is located at index %d%n%n"
,
32
letters.indexOf(
"hello"
)
);
33
34
// test lastIndexOf to find a substring in a string
35
System.out.printf(
"Last \"def\" is located at index %d%n"
,
36
letters.lastIndexOf(
"def"
)
);
37
System.out.printf(
"Last \"def\" is located at index %d%n"
,
38
letters.lastIndexOf(
"def"
,
25
)
);
39
System.out.printf(
"Last \"hello\" is located at index %d%n"
,
40
letters.lastIndexOf(
"hello"
)
);
41
}
42
}
// end class StringIndexMethods
'c' is located at index 2
'a' is located at index 13
'$' is located at index -1
Last 'c' is located at index 15
Last 'a' is located at index 13
Last '$' is located at index -1
"def" is located at index 3
"def" is located at index 16
"hello" is located at index -1
Last "def" is located at index 16
Last "def" is located at index 16
Last "hello" is located at index -1
Fig. 14.5
|
String-searching methods
indexOf
and
lastIndexOf
. (Part 2 of 2.)
All the searches in this example are performed on the
String
letters
(initialized with
"abcdefghijklmabcdefghijklm"
). Lines 11-16 use method
indexOf
to locate the first
occurrence of a character in a
String
. If the method finds the character, it returns the char-
acter's index in the
String
—otherwise, it returns
-1
. There are two versions of
indexOf
that search for characters in a
String
. The expression in line 12 uses the version of method
indexOf
that takes an integer representation of the character to find. The expression at line
14 uses another version of method
indexOf
, which takes two integer arguments—the
character and the starting index at which the search of the
String
should begin.