Indexof() searches for the first occurrence of character or substring
lastIndexOf() searches for the last occurence of a character or substring.
We can also specify a starting point from where we want to start searching using these forms
int indexOf(String str,int startIndex)
int lastIndexOf(String str,int startIndex)
METHOD 1:
class index{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Pro java tricks is website of java tutorials");
int start;
int end;
System.out.println(sb);
start =sb.indexOf("java");
System.out.println("starting Index="+start);
end =sb.lastIndexOf("java");
System.out.println("Ending Index="+end);
}
}
OUTPUT:
METHOD 2:
There is another way to search Substring or character in a string by using String buffer.it has two general form
String substring(int startIndex)
String substring(int startIndex,int endIndex)
First method is used when we only know the starting index of substring we want to search and second method is used when we know the starting and ending index of substring.
CODING:
{
public static void main(String args[])
{
String sb="Pro java tricks is website of java tutorials";
int start;
int end;
System.out.println(sb);
System.out.println("index of java="+sb.indexOf("java"));
System.out.println("Lastindex of java="+sb.lastIndexOf("java"));
System.out.println("index of (java,10)="+sb.indexOf("java",10));
}
}
No comments:
Post a Comment