publicclassStringToCharArray{publicstaticvoidmain(Stringargs[]){//1. Create a String variable and assign a valueStringcbm="CodeBlogMoney";intlengthOfString=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(inti=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 arrayfor(charvalueofChar: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(Stringargs[]){//1. Define a string object with valueStringcbm="CodeBlogMoney";//2.Use toCharArray() to return the array of characterschar[]arrayOfCharacters=cbm.toCharArray();// 3. Print the values of the character of array.for(charvalueofChar:arrayOfCharacters){System.out.println(valueofChar);}}}
Sharing is caring!