Java Reference
In-Depth Information
If a string contains the digits of a number, you use the
Integer.parseInt
or
Double.parseDouble
method to obtain the number value.
double price = Double.parseDouble(input);
//
price is the floating-point number 3.95
However, if the string contains spaces or other characters that cannot occur inside
numbers, an error occurs. For now, we will always assume that user input does not
contain invalid characters.
The
substring
method computes substrings of a string. The call
Use the
substring
method to extract a part of a
string
.
s.substring(start, pastEnd)
returns a string that is made up of the characters in the string
s
, starting at position
start
, and containing all characters up to, but not including, the position
pastEnd
.
Here is an example:
String greeting = "Hello, World!";
String sub = greeting.substring(0, 5); // sub is
"Hello"
The
substring
operation makes a string that consists of five characters taken from
the string
greeting
. A curious aspect of the
substring
operation is the
numbering of the starting and ending positions. The first string position is labeled 0,
the second one 1, and so on. For example,
Figure 3
shows the position numbers in the
greeting
string.
String positions are counted starting with 0.
The position number of the last character (12 for the string
ÐHello, World!Ñ
) is
always 1 less than the length of the string.
Let us figure out how to extract the substring
ÐWorldÑ
. Count characters starting at
0, not 1. You find that
W
, the eighth character, has position number 7. The first