Java Reference
In-Depth Information
public int
indexOf(String aString,
int
start)
Returns the index (position) of the fi rst occurrence of the string
aString
in the calling object
string that occurs at or after position
start.
Positions are counted 0, 1, 2, etc. Returns
−1
if
aString
is not found.
EXAMPLE
After program executes
String name = "Mary, Mary quite contrary";
name.indexOf("Mary", 1)
returns
6
.
The same value is returned if
1
is replaced by any number up to and including
6
.
name.indexOf("Mary", 0)
returns
0
.
name.indexOf("Mary", 8)
returns
−1
.
Throws:
NullPointerException
if
aString
is
null
.
public int
lastIndexOf(String aString)
Returns the index (position) of the last occurrence of the string
aString
in the calling object
string. Positions are counted 0, 1, 2, etc. Returns −
1
if
aString
is not found.
EXAMPLE
After program executes
String name = "Mary, Mary, Mary quite so";
greeting.indexOf("Mary")
returns
0
, and
name.lastIndexOf("Mary")
returns
12
.
Throws:
NullPointerException
if
aString
is
null
.
public int
length()
Returns the length of the calling object (which is a string) as a value of type
int.
EXAMPLE
After program executes
String greeting = "Hello!";
greeting.length()
returns
6
.
public
String substring(
int
start)
Returns the substring of the calling object string starting from
start
through to the end of the
calling object. Positions are counted 0, 1, 2, etc. Be sure to notice that the character at position
start
is included in the value returned.
EXAMPLE
After program executes
String sample = "AbcdefG";
sample.substring(2)
returns
"cdefG"
.
Throws:
IndexOutOfBoundsException
if
start
is negative or larger than the length of the
calling object.