Convert a String to an Array
There are many ways to convert a string to an array. The simplest way is to use the toCharArray() method:
Example
Convert a string to a char array:
java
// Create a string
String myStr = "Hello";
// Convert the string to a char array
char[] myArray = myStr.toCharArray();
// Print the first element of the array
System.out.println(myArray[0]);
Explanation: The method toCharArray() turns the string into an array of characters. Each letter of "Hello" becomes one element in the array, so myArray[0] is H.
You can also loop through the array to print all array elements:
Example
java
// Create a string
String myStr = "Hello";
// Convert the string to a char array
char[] myArray = myStr.toCharArray();
// Print array elements
for (char i : myArray) {
System.out.println(i);
}
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
- Java Strings Tutorial
- Java Array Tutorial
- The toCharArray() String Method