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>
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.
Where you start
public List<string> ParseCsvLine(string line) {
}
Worked examples
| Call | Result |
|---|---|
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;
}