Java Reference
In-Depth Information
19
20
for
(
int
count = s1.length() -
1
; count >=
0
; count--)
21
System.out.printf(
"%c "
,
s1.charAt(count)
);
22
23
// copy characters from string into charArray
24
s1.getChars(
0
,
5
, charArray,
0
);
25
System.out.printf(
"%nThe character array is: "
);
26
27
for
(
char
character : charArray)
28
System.out.print(character);
29
30
System.out.println();
31
}
32
}
// end class StringMiscellaneous
s1: hello there
Length of s1: 11
The string reversed is: e r e h t o l l e h
The character array is: hello
Fig. 14.2
|
String
methods
length
,
charAt
and
getChars
. (Part 2 of 2.)
Line 15 uses
String
method
length
to determine the number of characters in
String
s1
. Like arrays, strings know their own length. However, unlike arrays, you access a
String
's length via class
String
's
length
method.
Lines 20-21 print the characters of the
String
s1
in reverse order (and separated by
spaces).
String
method
charAt
(line 21) returns the character at a specific position in the
String
. Method
charAt
receives an integer argument that's used as the
index and returns
the character at that position. Like arrays, the first element of a
String
is at position 0.
Line 24 uses
String
method
getChars
to copy the characters of a
String
into a char-
acter array. The first argument is the starting index from which characters are to be copied.
The second argument is the index that's one past the last character to be copied from the
String
. The third argument is the character array into which the characters are to be
copied. The last argument is the starting index where the copied characters are placed in
the target character array. Next, lines 27-28 print the
char
array contents one character at
a time.
Chapter 19 discusses sorting and searching arrays. Frequently, the information being sort-
ed or searched consists of
String
s that must be compared to place them into order or to
determine whether a string appears in an array (or other collection). Class
String
provides
methods for
comparing
strings, as demonstrated in the next two examples.
To understand what it means for one string to be greater than or less than another,
consider the process of alphabetizing a series of last names. No doubt, you'd place “Jones”
before “Smith” because the first letter of “Jones” comes before the first letter of “Smith”
in the alphabet. But the alphabet is more than just a list of 26 letters—it's an
ordered
list
of characters. Each letter occurs in a specific position within the list. Z is more than just a
letter of the alphabet—it's specifically the twenty-sixth letter of the alphabet.