Splitting a string into an array
One method, and three behaviours that surprise people.
String csv = "alpha,beta,gamma";
String[] parts = csv.split(","); // ["alpha", "beta", "gamma"]
The delimiter is a regular expression
This is the trap. split takes a regex, not a literal, so characters with meaning in a regex must be escaped:
"1.2.3".split(".") // empty array — . matches everything
"1.2.3".split("\\.") // ["1", "2", "3"]
The same applies to |, +, *, ?, (, ), [, ], ^, $ and \. To be safe with a delimiter that comes from elsewhere:
text.split(Pattern.quote(delimiter));
It also means a regex is available when you want one — split("\\s+") splits on runs of whitespace, which is usually what you want for words.
Trailing empty strings are dropped
"a,b,,".split(",") // ["a", "b"] — two entries, not four
That is rarely what you want when parsing a CSV row, where a trailing empty field is meaningful. A negative limit keeps them:
"a,b,,".split(",", -1) // ["a", "b", "", ""]
A positive limit caps the number of pieces, leaving the rest unsplit in the final element:
"a,b,c".split(",", 2) // ["a", "b,c"]
That is useful for splitting key=value where the value may contain the separator.
Leading empty strings are kept
",a".split(",") // ["", "a"]
Asymmetric with the trailing case, and it catches people out often enough to be worth remembering.
Into characters
char[] chars = "hello".toCharArray();
For iteration you do not need the array:
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
}
Both work on UTF-16 code units, not characters. Anything outside the Basic Multilingual Plane — many emoji, some CJK — occupies two char values, so a per-char loop splits them. For text that may contain such characters, use s.codePoints().
Not a CSV parser
split(",") handles a simple list. It does not handle quoted fields containing commas, escaped quotes or embedded newlines. If the input is a real CSV file from elsewhere, use a CSV library — the format is much more awkward than it looks.