SwadhyAI Notes

All Java notes

How to Convert String to Array in Java

The Challenge

Convert a string into an array of characters or words!

Solutions

Method 1: String to Character Array

java
String text = "Hello";
char[] charArray = text.toCharArray();

for (char c : charArray) {
    System.out.print(c + " ");
}
// Output: H e l l o

Method 2: String to Word Array

java
String text = "Java is fun";
String[] words = text.split(" ");

for (String word : words) {
    System.out.println(word);
}
// Output:
// Java
// is
// fun

Method 3: Split by Custom Delimiter

java
String text = "apple,banana,cherry";
String[] fruits = text.split(",");

System.out.println(Arrays.toString(fruits));
// Output: [apple, banana, cherry]

Did You Know?

The split() method uses regex! Use split("\\.") to split by period (escape special characters).

Pro Tip

Split with limit to control array size:

java
String text = "a,b,c,d,e";
String[] parts = text.split(",", 3);
System.out.println(Arrays.toString(parts));
// Output: [a, b, c,d,e]

Real-World Use Cases

  • CSV parsing: Split comma-separated values
  • Text processing: Analyze individual characters
  • Data extraction: Parse structured text
  • Tokenization: Break text into tokens
›Short versionOpen if you only have a minute.
  • toCharArray() returns the char values. It does not split words.
  • split takes a regex. The dot matches any character.
  • "a.b.c".split(".") does not return ["a", "b", "c"]. Escape the dot as "\\.".
  • Repeated delimiters produce empty tokens. Decide whether those tokens are data.

String to array

Turn text into chars, or into tokens, depending on the next step.

Working approach

  • Use toCharArray when the next loop wants characters.
  • Use split with a regex you meant, and escape metacharacters.
  • Use a real CSV parser for CSV. split(",") breaks on quoted commas.

Walk the sample

  1. Input "a,b,c"
  2. The delimiter is a literal comma
  3. The array is ["a", "b", "c"]

The trap

split(".") looks like a literal dot and behaves as "split on every character". Default split then drops the trailing empty tokens.

java
String[] letters = "a.b.c".split("\\.");   // ["a", "b", "c"]
char[] chars = "a.b.c".toCharArray();         // five chars, including the dots

// "a.b.c".split(".") does not produce the three letters

What does "a.b.c".split(".") give you?

The pattern . matches any character, so every character is a delimiter.

The tokens between those delimiters are empty, and split discards trailing empties, so you do not get ["a", "b", "c"]. The escaped pattern "\\." does.

Time O(n), space O(n).

Easy to get wrong

  • Calling split(".") to split on a dot.
  • Using toCharArray when the next step wanted words.