Searching Strings

  • The String class have two methods to search a string for a character or a substring

    indexOf( ) Searches for the firstoccurrence of a character or substring.

    lastIndexOf( ) Searches for the last occurrence of a character or substring.

  • These two methods are overloaded in different forms but all will return the index value means int value where the character or sub string found in invoking string.

int indexOf(int ch)-To find the first occurrence of the character ch.

int lastIndexOf(int ch)-To find the last occurrence of the character ch.

int indexOf(String str)-To find first occurrence of a substring str.

int lastIndexOf(String str)-To find lastoccurrence of a substring str.

int indexOf(int ch, int startIndex)-To specify the starting point of search by startIndex for first occurrence.

int lastIndexOf(int ch, int startIndex)-To specify the starting point of search b ystartIndex for last occurrence.

int indexOf(String str, int startIndex)-To specify the starting pointof search by startIndex for first occurrence.

int lastIndexOf(String str, int startIndex)-To specify the starting point of search by startIndex for last occurrence.

// Demonstrate indexOf() and lastIndexOf().
public class IndexOfDemo
{
 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(t) = " + s.indexOf('t'));
   System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
 System.out.println("lastIndexOf(T) = " + s.lastIndexOf('T'));

 System.out.println("indexOf(the) = " + s.indexOf("the"));
 System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
   System.out.println("lastIndexOf(The) = " + s.lastIndexOf("The"));

 System.out.println("indexOf(t, 10) = " + s.indexOf('t', 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));
 }
}

Output:

Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
lastIndexOf(T) = -1
indexOf(the) = 7
lastIndexOf(the) = 55
lastIndexOf(The) = -1
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

results matching ""

    No results matching ""