There are multiple ways to convert a String to an array in Java. We can convert it to a char array or String array.
Convert a String to a char Array
The String class, a fundamental data type in Java, has the useful toCharArray() method that enables the conversion of a String to a char array. You can learn more about Java classes and objects in our tutorial Objects and Classes in Java.
Example
class Test {
public static void main(String[] args) {
String str = "alegrucoding.com";
char[] charArray = str.toCharArray();
for (char ch : charArray) {
System.out.print(ch + ",");
}
}
}
Output: a,l,e,g,r,u,c,o,d,i,n,g,.,c,o,m
It also can be done with a for-loop. We need first to create an empty array, iterate over the String’s chars, and add each char to the array.
Example
public static void main(String[] args) {
String str = "alegrucoding.com";
char[] charArray = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
charArray[i] = str.charAt(i);
}
for (char ch : charArray) {
System.out.print(ch + ",");
}
}
Output: a,l,e,g,r,u,c,o,d,i,n,g,.,c,o,m
Convert a String to a String Array
The easiest way to convert a String to a String Array is with the split() method. This method splits the string around matches of the given regular expression.
Example 1
Split the String by characters
class Test {
public static void main(String[] args) {
String str = "alegrucoding.com";
String[] strArray = str.split("");
Arrays.stream(strArray).forEach(item -> System.out.print(item + ","));
}
}
Output: a,l,e,g,r,u,c,o,d,i,n,g,.,c,o,m
Example 2
Split the String by white space
class Test {
public static void main(String[] args) {
String str = "Hello Java World";
String[] strArray = str.split(" ");
Arrays.stream(strArray).forEach(item -> System.out.print(item + ","));
}
}
Output: Hello,Java,World,
You can use whatever regex you want to split your String with the split() method.
Happy coding!