There are several ways by which characters can be extracted from String class object. String is treated as an object in Java so we can’t directly access the characters that comprise a string. For doing this String class provides various predefined methods.
Character Extraction in Java
charAt()
charAt() method is used to extract a single character at an index. It has following syntax.
Syntax
char charAt(int index)
Example
class temp { public static void main(String...s) { String str="Hello"; char ch=str.charAt(2); System.out.println(ch); } }
Output
l
In above example ch will contain character l. We must take care that the index should not be negative and should not exceed string length.
getChars()
It is used to extract more than one character. getChars() has following syntax.
Syntax
void getChars(int stringStart, int stringEnd, char arr[], int arrStart)
Here stringStart and stringEnd is the starting and ending index of the substring. arr is the character array that will contain the substring. It will contain the characters starting from stringStart to stringEnd-1. arrStart is the index inside arr at which substring will be copied. The arr array should be large enough to store the substring.
Example
class temp { public static void main(String...s) { String str="Hello World"; char ch[]=new char[4]; str.getChars(1,5,ch,0); System.out.println(ch); } }
Output
ello
getBytes()
getBytes() extract characters from String object and then convert the characters in a byte array. It has following syntax.
Syntax
byte [] getBytes()
Example
String str="Hello"; byte b[]=str.getBytes();
toCharArray()
It is an alternative of getChars() method. toCharArray() convert all the characters in a String object into an array of characters. It is the best and easiest way to convert string to character array. It has following syntax.
Syntax
char [] toCharArray()
Example
class temp { public static void main(String...s) { String str="Hello World"; char ch[]=str.toCharArray(); System.out.println(ch); } }
Output
Hello World
If you found anything wrong or have any doubts regarding above tutorial then comment below.