More about Strings

This chapter accompanies the previous one. Read it for even more info on Strings.

9. The indexOf() Methods


Answer:

erc

The second statement works like this:

buttercup

The final string could just as easily have been created with a single call:

    str = str.substring(4,7);

The indexOf() Methods

There are four varieties of indexOf() in the Java library. Only the following may be included on the AP examination:

indexOf( String str )
Returns the index of the first occurrence of str or -1 if str is not found.


For example, the following puts the value 4 into location.

String example = "The sea is calm to-night." ;
int location = example.indexOf( "sea" );

The following puts the value -1 into location.

String example = "The sea is calm to-night." ;
int location = example.indexOf( "rats" );


Question 9:

What does the following put into location?

    String example = "The sea is calm to-night." ; int location = example.indexOf( "a" );