
Convert String To Array in Java
Got it! Let's see how to convert a String to an Array in Java.
1. Convert String to Character Array
If you want each letter separately:
public class StringToCharArray { public static void main(String[] args) { String str = "Hello"; char[] charArray = str.toCharArray(); // Convert to character array // Print each character for (char c : charArray) { System.out.println(c); } }}
Output:
Hello
2. Convert String to String Array (Splitting by Space or Comma)
If you want to split a sentence or comma-separated values:
public class StringToStringArray { public static void main(String[] args) { String str = "apple banana cherry"; String[] words = str.split(" "); // Split by space // Print each word for (String word : words) { System.out.println(word); } }}
Output:
applebananacherry
You can split by comma too:
String str = "apple,banana,cherry";String[] fruits = str.split(",");
Quick Summary:
Task | Method |
---|---|
Convert to Character Array | toCharArray() |
Convert to String Array | split("delimiter") |
Would you like an example where both character array and string array are used together? ?
It can be really fun to see! ?