
This blog helps to convert Java String to a character array.
1. Logical Approach without any inbuilt functions.
Follow these steps:
- Create a String variable and assign a value.
- Use the length of the String variable to create an array of characters.
- Use a loop to iterate the String using an index.
- Assign a value at the index to a character array.
- Once loops complete, Characters array will be ready to use.
- Use a loop to print the character array.
Code:
public class StringToCharArray { public static void main( 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 = new char[ 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. Using toCharArray() 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
public class StringToCharArrayUsingInbuildMethod { public static void main( 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 ); } } }
Output of above code:
C o d e B l o g M o n e y
More articles to check out.
Few online string tools to check out.