Java Reference
In-Depth Information
Taking Strings Apart with Substrings
Problem
You want to break a string apart into substrings by position.
Solution
Use the
String
object's
substring()
method.
Discussion
The
substring()
method constructs a new
String
object made up of a run of characters
contained somewhere in the original string, the one whose
substring()
you called. The
substring
method is overloaded: both forms require a starting index (which is always
zero-
based
). The one-argument form returns from
startIndex
to the end. The two-argument
form takes an ending index (not a length, as in some languages), so that an index can be gen-
erated by the
String
methods
indexOf()
or
lastIndexOf()
.
WARNING
Note that the end index is one beyond the last character! Java adopts this “half open inter-
val” (or inclusive start, exclusive end) policy fairly consistently; there are good practical
reasons for adopting this approach, and some other languages do likewise.
public
public class
class
SubStringDemo
SubStringDemo
{
public
public static
void
main
(
String
[]
av
) {
String a
=
"Java is great."
;
System
.
out
.
println
(
a
);
String b
=
a
.
substring
(
5
);
static
void
// b is the String "is great."
System
.
out
.
println
(
b
);
String c
=
a
.
substring
(
5
,
7
);
// c is the String "is"
System
.
out
.
println
(
c
);
String d
=
a
.
substring
(
5
,
a
.
length
());
// d is "is great."
System
.
out
.
println
(
d
);
}
}