publicclassStringToCharArray{publicstaticvoidmain( String args[]){//1. Create a String variable and assign a value
String cbm ="CodeBlogMoney";int lengthOfString = cbm.length();//2.Use the length of the String variable to create an array of characters
char[] arrayOfCharacters =newchar[ lengthOfString ];// 3. Use a loop to iterate the String using an index.
for(int i =0; i < lengthOfString; i++){// 4 Assign a value at the index to a character array.
arrayOfCharacters[i]= cbm.charAt(i);}// 5. Once loops complete, Characters array will be ready to use.
// 6. Use a loop to print the character array
for(char valueofChar : arrayOfCharacters ){ System.out.println( valueofChar );}}}
Output of above code:
C
o
d
e
B
l
o
g
M
o
n
e
y
2. UsingtoCharArray()function
java.lang.String has toCharArray() which converts String to array of characters and return the new object of array.
Follow these steps
Define a string object with value.
Use toCharArray() to return the array of characters
Print the values of the character of array.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
publicclassStringToCharArrayUsingInbuildMethod{publicstaticvoidmain( String args[]){//1. Define a string object with value
String cbm ="CodeBlogMoney";//2.Use toCharArray() to return the array of characters
char[] arrayOfCharacters = cbm.toCharArray();// 3. Print the values of the character of array.
for(char valueofChar : arrayOfCharacters ){ System.out.println( valueofChar );}}}
Sharing is caring!