String to Char Array Java

Jun 7, 2020

2 mins read

Published in
String to Char Array Java

This blog helps to convert Java String to a character array.

1. Logical Approach without any inbuilt functions.

Follow these steps:

  1. Create a String variable and assign a value.
  2. Use the length of the String variable to create an array of characters.
  3. Use a loop to iterate the String using an index.
  4. Assign a value at the index to a character array.
  5. Once loops complete, Characters array will be ready to use.
  6. Use a loop to print the character array.

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

  1. Define a string object with value.
  2. Use toCharArray() to return the array of characters
  3. 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
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.

https://codebeautify.org/string-functions

Sharing is caring!