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);
int lastIndexOf(int ch);
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);
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