Tuesday, 19 May 2015

Filled Under:

How To Search String With in String In Java

The string class provide several methods to search a string for specified substring.it has two general methods 
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:

class index
{
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));
}

}


OUTPUT:













0 comments:

Post a Comment