Split one CSV line properly
An import job reads a CSV where some fields legitimately contain commas, so splitting on the comma alone corrupts the data.
- Commas separate fields, except inside a double-quoted field.
- Inside a quoted field, two double quotes in a row mean one literal quote.
- The quotes themselves are not part of the value.
- An empty line gives an empty list; an empty field between two commas gives an empty string.
parseCsvLine(line: string) → list<string>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
List<String> parseCsvLine(String line) {
}
Worked examples
| Call | Result |
|---|---|
parseCsvLine("a,b,c") | Main.<String>ls("a", "b", "c") |
parseCsvLine("a,\"b,c\",d") | Main.<String>ls("a", "b,c", "d") |
parseCsvLine("\"say \"\"hi\"\"\",x") | Main.<String>ls("say \"hi\"", "x") |
parseCsvLine("a,,b") | Main.<String>ls("a", "", "b") |
Hint
Walk the line one character at a time carrying a single boolean: are we inside quotes right now.
Reference solution in Java
List<String> parseCsvLine(String line) {
if (line.isEmpty()) return new ArrayList<>();
List<String> fields = new ArrayList<>();
StringBuilder cur = new StringBuilder();
boolean quoted = false;
int i = 0;
while (i < line.length()) {
char c = line.charAt(i);
if (quoted) {
if (c == '"') {
if (i + 1 < line.length() && line.charAt(i + 1) == '"') { cur.append('"'); i += 2; continue; }
quoted = false; i++; continue;
}
cur.append(c); i++;
} else if (c == '"') { quoted = true; i++; }
else if (c == ',') { fields.add(cur.toString()); cur.setLength(0); i++; }
else { cur.append(c); i++; }
}
fields.add(cur.toString());
return fields;
}