Here we are converting a string into a primitive datatype. It is recommended to have good knowledge of Wrapper classes and concepts like autoboxing and unboxing as in java they are frequently used in converting data types.
Illustrations:
Input : Hello World Output : [H, e, l, l, o, W, o, r, l, d]
Input : GeeksForGeeks Output : [G, e, e, k, s, F, o, r, G, e, e, k, s]
Different Ways of Converting a String to Character Array
- Using a naive approach via loops
- Using toChar() method of String class
Way 1: Using a Naive Approach
- Get the string.
- Create a character array of the same length as of string.
- Traverse over the string to copy character at the i’th index of string to i’th index in the array.
- Return or perform the operation on the character array.
Example:
Java
// Java Program to Convert a String to Character Array // Using Naive Approach // Importing required classes import java.util.*; // Class public class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "GeeksForGeeks" ; // Creating array of string length // using length() method char [] ch = new char [str.length()]; // Copying character by character into array // using for each loop for ( int i = 0 ; i < str.length(); i++) { ch[i] = str.charAt(i); } // Printing the elements of array // using for each loop for ( char c : ch) { System.out.println(c); } } } |
G e e k s F o r G e e k s
Way 2: Using toCharArray() Method
Tip: This method acts very important as in most interviews an approach is seen mostly laid through via this method.
Procedure:
- Getting the string.
- Creating a character array of the same length as of string.
- Storing the array return by toCharArray() method.
- Returning or performing an operation on a character array.
Example:
Java
// Java Program to Convert a String to Character Array // Using toCharArray() Method // Importing required classes import java.util.*; // Class public class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "GeeksForGeeks" ; // Creating array and storing the array // returned by toCharArray() method char [] ch = str.toCharArray(); // Lastly printing the array elements for ( char c : ch) { System.out.println(c); } } } |
G e e k s F o r G e e k s