Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaConvert a String to Character Array in Java

Convert a String to Character Array in Java

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

  1. Using a naive approach via loops
  2. Using toChar() method of String class

Way 1: Using a Naive Approach

  1. Get the string.
  2. Create a character array of the same length as of string.
  3. Traverse over the string to copy character at the i’th index of string to i’th index in the array.
  4. 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);
        }
    }
}


Output

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:

  1. Getting the string.
  2. Creating a character array of the same length as of string.
  3. Storing the array return by toCharArray() method.
  4. 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);
        }
    }
}


Output

G
e
e
k
s
F
o
r
G
e
e
k
s
RELATED ARTICLES

Most Popular

Recent Comments