If you want a quick way to split a string into an array where each character is a separate element, the easiest way is using split("")
. This will break the string at every character and return an array of strings.
public class Main {
public static void main(String[] args) {
String word = "name";
String[] letters = word.split("");
for (String letter : letters) {
System.out.println(letter);
}
}
}
Why use this?
- Quick and built-in—no need to loop manually.
- Works perfectly for breaking a string into an array of single-character strings.
When to avoid?
- If you need a
char[]
instead ofString[]
, this method won’t work. -
split("")
relies on regex, which might have performance implications for large strings.