Java Reference
In-Depth Information
character that you don't want, !, is the character at position 12 (see
Figure 4
).
Therefore, the appropriate substring command is
String sub2 = greeting.substring(7, 12);
Figure 4
Extracting a Substring
It is curious that you must specify the position of the first character that you do
want
and then the first character that you don't want. There is one advantage to this
setup.
You can easily compute the length of the substring: It is
pastEnd
-
start
. For
example, the string
ÐWorldÑ
has length 12 ɨ 7 62 5.
159
160
If you omit the second parameter of the
substring
method, then all characters
from the starting position to the end of the string are copied. For example,
String tail = greeting.substring(7);
// Copies all characters
from position 7 on
sets tail to the string "World!".
If you supply an illegal string position (a negative number, or a value that is larger
than the length of the string), then your program terminates with an error message.
In this section, we have made the assumption that each character in a string occupies
a single position. Unfortunately, that assumption is not quite correct. If you process
strings that contain characters from international alphabets or special symbols, some
characters may occupy two positionsȌsee
Advanced Topic 4.5
.
S
ELF
C
HECK
13.
Assuming the
String
variable
s
holds the value
ÐAgentÑ
, what is
the effect of the assignments
s = s + s.length()?