Java Reference
In-Depth Information
We can then search for the next occurrence of the substring by passing the new value of index to the
method indexOf() . The loop continues as long as the index value returned is not -1.
To count the occurrences of the substring " the " the program searches the string text backwards, by
using the method lastIndexOf() instead of indexOf() . This works in much the same way, the only
significant difference being that we decrement the value of index , instead of incrementing it. This is
because the next occurrence of the substring has to be at least that many characters back from the first
character of the substring we have just found. If the string " the " happened to occur at the beginning of
the string we are searching, the lastIndexOf() method would be called with a negative value for
index . This would not cause any problem - it would just result in -1 being returned in any event.
Extracting Substrings
The String class includes a method, substring() , that will extract a substring from a string. There are
two versions of this method. The first version will extract a substring consisting of all the characters from a
given index position to the end of the string. This works as illustrated in the following code fragment:
String place = "Palm Springs";
String lastWord = place.substring(5);
After executing these statements, lastWord will contain the string Springs . The substring is copied
from the original to form a new string. This is useful when a string has basically two constituent
substrings, but a more common requirement is to extract several substrings from a string where each
substring is separated from the next by a special character such as a comma, a slash, or even just a
space. The second version of substring() will help with this.
You can extract a substring from a string by specifying the index positions of the first character in the
substring and one beyond the last character of the substring as arguments to the method
substring() . With the variable place being defined as before, the following statement will result in
the variable segment being set to the string " ring ":
String segment = place.substring(7, 11);
The substring() method is not like the indexOf() method when it comes to
illegal index values. With either version of the method substring() , if you specify
an index that is outside the bounds of the string, you will get an error. As with the
charAt() method, substring() will throw a
StringIndexOutOfBoundsException exception.
We can see how substring() works with a more substantial example.
Try It Out - Word for Word
We can use the indexOf() method in combination with the substring() method to extract a
sequence of substrings that are separated by spaces from a single string:
Search WWH ::




Custom Search