In how many ways we can convert a String to a character array using Java?


You can convert a String to a character array either by copying each element of the String to an array or, using the toCharArray() method.

Copying each element

  • Get the String to be converted.

  • Create an empty character array with the length of the String.

  • The charAt() method of the String class returns the character at a particular position. Using this method copy each character of the String to the array.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class StringToCharArray {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      //Creating an empty array with the length of the String
      char chArray[] = new char[str.length()];
      //Copying each element of the String to the array
      for(int i=0; i<str.length(); i++) {
         chArray[i] = str.charAt(i);
      }
      System.out.println("Contents of the character array: ");
      System.out.println(Arrays.toString(chArray));
   }
}

Output

Enter a String value:
Tutorialspoint
Contents of the String array:
[T, u, t, o, r, i, a, l, s, p, o, i, n, t]

Using toCharArray() method

The toCharArray() method of the Strong class converts the current String into a character array and returns it. Therefore, to convert a Sting into a character array using this method −

  • Get the String to be converted.

  • Create an empty character array with the length of the String.

  • Convert the String to character array using the toCharArray() method and store it in the above created empty array.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class ToCharArrayExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      //Creating an empty array with the length of the String
      char chArray[] = str.toCharArray();
      System.out.println("Contents of the character array: ");
      System.out.println(Arrays.toString(chArray));
   }
}

Output

Enter a String value:
Tutorialspoint
Contents of the character array:
[T, u, t, o, r, i, a, l, s, p, o, i, n, t]

Updated on: 10-Oct-2019

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements