JavaHow To Convert a String to an Array
Convert a String to an Array
There are many ways to convert a string to an array. The simplest way is to use thetoCharArray() method:
Example
Convert a string to achar array:
// Create a stringString myStr = "Hello";// Convert the string to a char arraychar[] myArray = myStr.toCharArray();// Print the first element of the arraySystem.out.println(myArray[0]);Try it Yourself »Explanation: The methodtoCharArray() turns the string into an array of characters. Each letter of"Hello" becomes one element in the array, somyArray[0] isH.
You can also loop through the array to print all array elements:
Example
// Create a stringString myStr = "Hello";// Convert the string to a char arraychar[] myArray = myStr.toCharArray();// Print array elementsfor (char i : myArray) { System.out.println(i);}Try it Yourself »Explanation: The loop goes through each element in the array and prints it. So for"Hello", it prints the letters one by one: H, e, l, l, o.
Related Pages
The toCharArray() String Method

