Drill

ProblemsC# › text

Split one CSV line properly

hardtextStringsParsingSimulationC#

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>

C# 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

public List<string> ParseCsvLine(string line) {
    
}

Worked examples

CallResult
ParseCsvLine("a,b,c")new List<string> { "a", "b", "c" }
ParseCsvLine("a,\"b,c\",d")new List<string> { "a", "b,c", "d" }
ParseCsvLine("\"say \"\"hi\"\"\",x")new List<string> { "say \"hi\"", "x" }
ParseCsvLine("a,,b")new List<string> { "a", "", "b" }

Hint

Walk the line one character at a time carrying a single boolean: are we inside quotes right now.

Reference solution in C#
public List<string> ParseCsvLine(string line) {
    if (line.Length == 0) return new List<string>();
    var fields = new List<string>();
    var cur = new StringBuilder();
    bool quoted = false;
    int i = 0;
    while (i < line.Length) {
        char c = line[i];
        if (quoted) {
            if (c == '"') {
                if (i + 1 < line.Length && line[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.Clear(); i++; }
        else { cur.Append(c); i++; }
    }
    fields.Add(cur.ToString());
    return fields;
}

The same problem in another language

More text problems in C#