In several ways, we can copy the charaters of a string object into an character array. (ie. converting the string to an array of characters.) Using the following String methods we can convert the string to an array of characters
charAt(i);
toCharArray();
getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) .
The following code illustrates how to convert String to array of charaters using above 3 methods.*/
public class StringToChrArray {
public static void main(String[] args) {
String inputString = "Techlabs4u.com";
int len = inputString.length();
char[] charArray1 = new char[len];
char[] charArray3 = new char[len];
// Converting using String to array of chars using charAt(i);
for (int i = 0; i < len; i++) {
charArray1[i] = inputString.charAt(i);
}
// Converting String to array of chars using toCharArray();
char[] charArray2=inputString.toCharArray();
// Converting String to array of chars using getChars();
inputString.getChars( 0, len, charArray3, 0) ;
System.out.println("From charArray1\n");
for (char c:charArray1) System.out.println(c);
System.out.println("From charArray2\n");
for (char c:charArray2) System.out.println(c);
System.out.println("From charArray3\n");
for (char c:charArray3) System.out.println(c);
}
}
Running the above program will output the following
java StringToChrArray
From charArray1
T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray2
T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray3
T
e
c
h
l
a
b
s
4
u
.
c
o
m
0 comments:
Post a Comment