Java Reference
In-Depth Information
0123456789 0 1 2 3 4
We l
Indices
Message
c ome
t o
J a v a
message.substring(0, 11) message.substring(11)
F
IGURE
4.2
The
substring
method obtains a substring from a string.
Note
If
beginIndex
is
endIndex
,
substring(beginIndex, endIndex)
returns an
empty string with length
0
. If
beginIndex
>
endIndex
, it would be a runtime error.
beginIndex <= endIndex
4.4.9 Finding a Character or a Substring in a String
The
String
class provides several versions of
indexOf
and
lastIndexOf
methods to find
a character or a substring in a string, as shown in TableĀ 4.10.
T
ABLE
4.10
The
String
class contains the methods for finding substrings.
Method Description
index(ch)
Returns the index of the first occurrence of
ch
in the string. Returns
-1
if not matched.
indexOf(ch, fromIndex)
Returns the index of the first occurrence of
ch
after
fromIndex
in the string. Returns
-1
if not matched.
indexOf(s)
Returns the index of the first occurrence of string
s
in this string. Returns
-1
if not matched.
indexOf(s, fromIndex)
Returns the index of the first occurrence of string
s
in this string after
fromIndex
. Returns
-1
if not
matched.
lastIndexOf(ch)
Returns the index of the last occurrence of
ch
in the string. Returns
-1
if not matched.
lastIndexOf(ch, fromIndex)
Returns the index of the last occurrence of
ch
before
fromIndex
in this string. Returns
-1
if not
matched.
Returns the index of the last occurrence of string
s
. Returns
-1
if not matched.
lastIndexOf(s)
Returns the index of the last occurrence of string
s
before
fromIndex
. Returns
-1
if not matched.
lastIndexOf(s, fromIndex)
For example,
"Welcome to Java".indexOf('W')
returns
0
.
"Welcome to Java".indexOf('o')
returns
4
.
"Welcome to Java".indexOf('o', 5)
returns
9
.
"Welcome to Java".indexOf("come")
returns
3
.
"Welcome to Java".indexOf("Java", 5)
returns
11
.
"Welcome to Java".indexOf("java", 5)
returns
-1
.
indexOf
"Welcome to Java".lastIndexOf('W')
returns
0
.
"Welcome to Java".lastIndexOf('o')
returns
9
.
"Welcome to Java".lastIndexOf('o', 5)
returns
4
.
"Welcome to Java".lastIndexOf("come")
returns
3
.
"Welcome to Java".lastIndexOf("Java", 5)
returns
-1
.
"Welcome to Java".lastIndexOf("Java")
returns
11
.
lastIndexOf
Suppose a string
s
contains the first name and last name separated by a space. You can use the
following code to extract the first name and last name from the string:
int
k = s.indexOf(
' '
);
String firstName = s.substring(
0
, k);
String lastName = s.substring(k +
1
);
Search WWH ::
Custom Search