Tuesday, December 13, 2011

How to Extract Characters from a String in java?

          A String is a collection of individual characters. A character can be an alphabet, a digit or even a space. We can extract a single or multiple character(s) from a String. The following methods are used to extract characters from a string.

1. charAt();
2. getChars();

charAt():
The charAt() method is used to extract a single character from a String.

Example--
String s=“ Sample ”;
char c=s.charAt(1);
     The charAt() method will extract a single character of the String based on the index.In this example the index is 1.So it will extract the 2nd character 'a'.Because index starts from 0.
Example:
class extract
{
public static void main(String args[])
{
String s="Sample";
char c=s.charAt(1);
System.out.println("The character extracted is "+c);
}
}

Output:
The character extracted is a

getChars():
The getChars() method extracts multiple characters from the String.

Syntax:
getChars(int StartPos, int EndPos, TargetArrayString, int StartArrayIndex);

          Let us suppose that we have a string “Datamining”. You have to extract four characters “mini” from the string.For that starting position is 4 and ending position is 8.Here we are extracting multiple characters. Thus a character’s array is needed (An Array of characters can store as many characters as you wish!)

class extract
{
public static void main(String args[])
{
String s="Datamining";
char ch[]=new char[5];
s.getChars(4,8,ch,0);
System.out.println(ch);
}
}

Output:
mini