Character Extraction
- We can extract a character from a string by using index values where characters are stored in such manner which is starts with zero.
charAt( )
- To extract a character from a string we can directly refer it using this method
char charAt(int where)
- where is the index to specify where the character is specified in a String.
- It will return a character at the specified index.
getChars( )
- We can extract more than one character at a time by using this method with the following general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
- sourceStart specifies the index of the beginning of the substring.
sourceEnd specifies an index that is one past the end of the desired substring.
The array that will receive the characters is specified bytarget.
The index within targetatwhich the substring will be copied is passed in targetStart.
getBytes( )
- _It _t stores the characters in an array of bytes.
- it uses the default character-to-byte conversions provided by the platform. The general form is:
byte[ ] getBytes( )
- It is most useful when we are exporting a String value into an environment that does not support 16-bit Unicode characters.
toCharArray( )
- It is used to convert all the characters in a String object into a character array.
- It returns an array of characters for the entire string with the following general form:
char[ ] toCharArray( )
public class CharacterExtraction
{
public static void main(String args[])
{
String str="Hello World";
char ch1 = str.charAt(3);
char ch2= "Bhuvana".charAt(2);
System.out.println("charAt() method output is::"+ch1);
System.out.println("charAt() method output is::"+ch2);
int start = 2;
int end = 6;
char buf[] = new char[end - start];
str.getChars(start,end,buf,0);
System.out.println("getChars() method ouptput is::");
System.out.println(buf);
System.out.println();
byte barr[] = str.getBytes();
for(int i=0;i<str.length();i++)
System.out.print(barr[i]);
System.out.println();
char chararray[] = str.toCharArray();
System.out.println(chararray);
}
}
Output:
charAt() method output is::l
charAt() method output is::u
getChars() method ouptput is::
llo
721011081081113287111114108100
Hello World