Introduced in 1.5 version.
When working with strings, you often need to search within a given string. There are several overloaded versions of the method indexOf() available in the String class for searching a string forward, the lastIndexOf() method for searching a string backward, and the regionMatches() method for comparing a region of text within a string. We"ll discuss each of these methods in turn.
How do you search for a particular character within a string and, if it occurs, at what position? For example, which index position does the character J occupy in the string "OCPJP"? The following program contains the code that uses the indexOf() method to answer this question.
Quite easy, right? The indexOf() method searches the specified character here it is, the character and returns the first occurrence of the character (note that the index starts from 0, not 1!). Now, let's search a substring within in a given string. The indexOf() method is overloaded, and one definition of the method takes a string as a search argument. Listing 7-2 shows an example.
(Please note that we used the escape character, \, to print for within double quotes.). What will happen if the search string does not exist in the string? For instance, if you search "fort instead of for in above example, you"ll get this result:
Substring "for" occurs at index: -1
Well, a failed indexOf search results in the value 1, indicating "not found".
These two were simple problems; now let try a slightly harder one. Given a big string, how can you find how many times a given string (say am) occurs within that string? Not to worry in this case there is another version of the indexOf() method.
In this method you can specify an index from which the search should commence. The following program shows the implementation.
It uses a while loop to check whether more occurrences of the search string exist in the input string. It also maintains an index from which you search ahead. It increments the index variable after each occurrence of the search string so that the next occurrence of the search string can be found. If you want to search the last occurrence of the search string, you can use the overloaded versions of the lastIndexOf() method defined in the String class.❮ Previous Next ❯