Drill

ProblemsJava › text

Split one CSV line properly

hardtextStringsParsingSimulationJava

An import job reads a CSV where some fields legitimately contain commas, so splitting on the comma alone corrupts the data.

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.

Solve it in Python →

Where you start

List<String> parseCsvLine(String line) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More text problems in Java