Convert a string to character array in Java

getChars(int startpos,int endpos,char[] destination,int destinationstartpos) and toCharArray() methods of String class can be used to convert a string to character array.

Start position and the end position of the String that to be copied, destination character array variable and starting position of destination variable are passed as arguments in getChars method.


Example 1 (getChars)

class StringTest{

public static void main(String args[]){

String str="Interesting";

char strtoch[]=new char[10];

str.getChars(2,5,strtoch,0);

for(int i=0;i<6;i++){

System.out.println(strtoch[i]);

}

}

}

Output 1

t

e

r


Example 2 (getChars)

class StringTest{

public static void main(String args[]){

String str="ABCDEFGH";

char strtoch[]=new char[8];

strtoch[0]='a';

strtoch[1]='b';

str.getChars(2,8,strtoch,2);

for(int i=0;i<8;i++){

System.out.println(strtoch[i]);

}

}

}

Output 2

a

b

C

D

E

F

G

H


Example 3 (toCharArray)

class StringTest{

public static void main(String args[]){

String string="Hi dude";

char[] strtochar=string.toCharArray();

int length=string.length();

for(int i=0;i<length;i++){

System.out.println(strtochar[i]);

}

}

}

Output 3

H

i

d

u

d

e