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