π Java: How to Convert a String to an Array (With Examples)
π§² Introduction β Why Convert a String to an Array?
Converting a string into an array is a common task in Java programming. Whether you’re analyzing individual characters, splitting words, or processing CSV-like input β breaking down strings into arrays is essential for data parsing and transformation.
β In this guide, youβll learn:
- How to convert a string to a character array
- How to split a string into a word array
- How to split by custom delimiters (comma, hyphen, etc.)
- How to handle edge cases and best practices
π‘ Method 1: Convert String to Character Array
public class StringToCharArray {
public static void main(String[] args) {
String str = "Java";
char[] chars = str.toCharArray();
for (char c : chars) {
System.out.print(c + " ");
}
}
}
β Explanation:
toCharArray()converts aStringinto an array of characters.- Great for character-level operations, such as reverse, encryption, or counting.
π§Ύ Method 2: Convert String to String Array (Split by Space)
public class StringToWordArray {
public static void main(String[] args) {
String sentence = "Java is awesome";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
β Explanation:
split(" ")breaks the string into substrings (words) by space.- Suitable for word processing and natural language operations.
π§ Method 3: Split String by Comma or Other Delimiters
public class SplitByComma {
public static void main(String[] args) {
String data = "apple,banana,grape";
String[] fruits = data.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
β Explanation:
- Use
split(",")for comma-separated strings (e.g., CSV). - You can also use other delimiters like
"\\|","-",":", etc.
π Common Delimiters:
| Delimiter | Pattern |
|---|---|
| Comma | "," |
| Space | " " or "\\s+" |
| Pipe | `”\ |
| Tab | "\\t" |
π Method 4: Convert String of Digits to Integer Array
public class StringToIntArray {
public static void main(String[] args) {
String digits = "1 2 3 4 5";
String[] parts = digits.split(" ");
int[] numbers = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
numbers[i] = Integer.parseInt(parts[i]);
}
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
β Explanation:
- Splits a space-separated string.
- Parses each substring into an integer using
Integer.parseInt().
β οΈ Warning: Make sure the input only contains numbers, or handle exceptions using try-catch.
π§Ό Best Practices
- β
Always
trim()the string if unsure of leading/trailing spaces. - β
Use regex like
"\\s+"to split on any whitespace. - β Validate numeric conversions using try-catch blocks to avoid
NumberFormatException. - β
Use
toCharArray()only for per-character logic β not for token parsing.
π Summary β Convert String to Array
Java provides powerful and flexible tools for breaking down strings into arrays β whether itβs characters, words, or numbers.
π§Ύ Key Takeaways:
- Use
.toCharArray()for character-level operations - Use
.split()for word/token-based splitting - Convert split strings to
int[]ordouble[]withparseInt()/parseDouble() - Choose the delimiter based on your use case (
" ",",","\\|", etc.)
βFAQs β Convert String to Array in Java
β How do I convert a string to a character array in Java?
Use toCharArray() method: char[] arr = str.toCharArray();.
β What is the difference between toCharArray() and split()?
toCharArray()splits a string into individual characters.split()breaks a string by delimiters (spaces, commas, etc.).
β How do I convert a comma-separated string to an array?
Use split(","):
String[] arr = str.split(",");
β Can I convert a string of numbers to an int[]?
Yes. First split the string and then use Integer.parseInt() in a loop.
β How do I split a string by multiple spaces?
Use regex split("\\s+").
Share Now :
