Java Reference
In-Depth Information
ison
String
. The third argument is the starting index in the comparison
String
. The last
argument is the number of characters to compare between the two
String
s. The method
returns
true
only if the specified number of characters are lexicographically equal.
Finally, the condition at line 54 uses a five-argument version of
String
method
regionMatches
to compare portions of two
String
s for equality. When the first argument
is
true
, the method ignores the case of the characters being compared. The remaining
arguments are identical to those described for the four-argument
regionMatches
method.
String
Methods
startsWith
and
endsWith
The next example (Fig. 14.4) demonstrates
String
methods
startsWith
and
endsWith
.
Method
main
creates array
strings
containing
"started"
,
"starting"
,
"ended"
and
"end-
ing"
. The remainder of method
main
consists of three
for
statements that test the elements
of the array to determine whether they start with or end with a particular set of characters.
1
// Fig. 14.4: StringStartEnd.java
2
// String methods startsWith and endsWith.
3
4
public class
StringStartEnd
5
{
6
public static void
main(String[] args)
7
{
8
String[] strings = {
"started"
,
"starting"
,
"ended"
,
"ending"
};
9
10
// test method startsWith
11
for
(String string : strings)
12
{
13
if
(
string.startsWith(
"st"
)
)
14
System.out.printf(
"\"%s\" starts with \"st\"%n"
, string);
15
}
16
17
System.out.println();
18
19
// test method startsWith starting from position 2 of string
20
for
(String string : strings)
21
{
22
if
(
string.startsWith(
"art"
,
2
)
)
23
System.out.printf(
24
"\"%s\" starts with \"art\" at position 2%n"
, string);
25
}
26
27
System.out.println();
28
29
// test method endsWith
30
for
(String string : strings)
31
{
32
if
(
string.endsWith(
"ed"
)
)
33
System.out.printf(
"\"%s\" ends with \"ed\"%n"
, string);
34
}
35
}
36
}
// end class StringStartEnd
Fig. 14.4
|
String
methods
startsWith
and
endsWith
. (Part 1 of 2.)