Friday 10 February 2017

Java Searching String



The String Searching Method:

  The Java String class provides methods to search for a specific character in a String or substring. These are indexOf() and lastIndexOf().
 The method indexOf() search for the first occurrence of a character or substring and return its position. The general form is:

int indexOf(int ch);

 the method lastIndexOf() searches for the last occurrence of a character or a substring and return its postion. The general form is:

int lastIndexOf(int ch);

 where ch is in both the methods is the character being searched for.
You can also specify the starting point in both the methods which take the general form is:

int lastIndexOf(int ch, int startIndex);
int lastIndexOf(String str, int startIndex);

Consider the following example:

IndexOfTest.java

 class IndexOfTest
 {
  public static void main(String arg[])
  {
    String str="Learning Java is fun";

    System.out.println(str);
    System.out.println("indexOf(n) is:"+str.indexOf('n'));
    System.out.println("indexOf(n,8) is:"+str.indexOf('n',8));

    System.out.println("lastIndexOf(n) is:"+str.lastIndexOf('n'));
    System.out.println("lastIndexOf(n,8) is:"+str.lastIndexOf('n',8));
  }
 }

The output generated by the above program is:
Learning Java is fun
indexOf(n) is:4
indexOf(n,8) is:19
lastIndexOf(n) is:19
lastIndexOf(n,8) is:6





 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats