String Searching in java


The string class provides two methods that allow you to search a string for a specific character or substring:

These two methods are overloaded in different ways. In all cases, the methods return the index to which the letter or substring returns and -1 in case of failure.

To search for the first appearance of the character, use

int indexOf(int ch)

To search for the last appearance of the character, use

int lastIndexOf(int ch)

To search for the first or last appearance of a substring, use

int indexOf(String str)
int lastIndexOf(String str)

You can specify a starting point for search using these forms:

int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)

int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

Here the Start Index indicates where the search begins. The search for indexOf () starts with startIndex at the end of the start. The search for lastIndexOf () moves from the startIndex to zero.


Example

Program
public class Main 
{
  public static void main(String[] args) 
  {
   String s = "Now is the time for all good men"+
              "to come to the aid of their country.";
   System.out.println(s);
   System.out.println("indexOf(i) = "+s.indexOf('i'));
   System.out.println("lastIndexOf(o) = "+s.lastIndexOf('o'));
   System.out.println("indexOf(the) = "+s.indexOf("the"));
   System.out.println("lastIndexOf(the) = "+s.lastIndexOf("the"));
   System.out.println("indexOf(i, 10) = "+s.indexOf('i',10));
   System.out.println("lastIndexOf(t,60) = "+s.lastIndexOf('t',60));
   System.out.println("indexOf(the, 10) = "+s.indexOf("the",10));
   System.out.println("lastIndexOf(the, 60) = "+s.lastIndexOf("the",60));
  }
}