Java Reference
In-Depth Information
The four flavors of the lastIndexOf() method have the same parameters as the four versions of the
indexOf() method. The difference is that the last occurrence of the character or substring that is
sought is returned by the lastIndexOf() method.
The method startsWith() that we mentioned earlier also comes in a version that accepts an
additional argument that is an offset from the beginning of the string being checked. The check for the
matching character sequence then begins at that offset position. If you have defined a string as:
String string1 = "The Ides of March";
then the expression String1.startsWith("Ides", 4) will have the value true .
We can show the indexOf() and lastIndexOf() methods at work with substrings in an example.
Try It Out - Exciting Concordance Entries
We'll use the indexOf() method to search the quotation we used in the last example for " and " and the
lastIndexOf() method to search for " the ".
public class FindCharacters {
public static void main(String[] args) {
// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+ " Whether 'tis nobler in the mind to suffer"
+ " the slings and arrows of outrageous fortune,"
+ " or to take arms against a sea of troubles,"
+ " and by opposing end them?";
int andCount = 0; // Number of ands
int theCount = 0; // Number of thes
int index = -1; // Current index position
String andStr = "and"; // Search substring
String theStr = "the"; // Search substring
// Search forwards for "and"
index = text.indexOf(andStr); // Find first 'and'
while(index >= 0) {
++andCount;
index += andStr.length(); // Step to position after last 'and'
index = text.indexOf(andStr, index);
}
// Search backwards for "the"
index = text.lastIndexOf(theStr); // Find last 'the'
while(index >= 0) {
++theCount;
index -= theStr.length(); // Step to position before last 'the'
index = text.lastIndexOf(theStr, index);
}
Search WWH ::




Custom Search