Sunday, 8 February 2015

How to extract words or cahracter form string in java

Fortunately in java the String class provide a number of ways in which characters can be extracted.Each is examined in this tutorial.

Use of charAt in Java:

To extract a single character from string we use charAt() its general form is
char charAt(int where)
where is the index of character that we want to obtain within the string 

Use of getChars() in java:

If we want to extract more than one character,than we use getschars() its general method is given below
void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
source start and sourceend specify starting and ending index of desired substring respectively.while char target specify from which array character has to be extract following program demonstrate these two methods.

CODING:


class get
{
public static void main(String args[])
{
String s ="Pro java Tricks provide free tutorial";
int start=4;
int end = 8;
char buf[]= new char[end-start];
char ch;
ch=s.charAt(4);
s.getChars(start,end,buf,0);
System.out.print("Extracted word:");
System.out.print(buf);
System.out.println("Extracted Character:"+ch);

}
}


OUTPUT:



No comments:

Post a Comment