Maintained by Vikas Dulgunde, software engineer
You are given a single line of comma-separated values as a string. The task is to break it into the individual field values it contains. A plain comma in the line marks the boundary between two fields.
Any field may be wrapped in double quotes. When a field is quoted, commas inside the quotes are part of the value rather than separators, so a quoted field can hold commas without being split. The quote characters themselves are markers and never belong in the returned value.
Return the fields in order, with the surrounding quotes removed. You do not need to handle escaped quotes (a doubled quote pair) inside a quoted field, and the input contains only printable ASCII.
An empty input string represents one line with a single empty field, so the result is a list holding one empty string.
No quotes appear, so the two commas split the line into three plain fields.
The first field is quoted, so its inner comma stays inside the value; the quotes are stripped, then the unquoted comma separates the second field.
Two commas with nothing between them produce an empty middle field rather than collapsing.
Visible test cases
Walk the string one character at a time and build the current field as you go, instead of trying to split on commas all at once.
Keep a boolean flag for whether you are currently inside a quoted region. A comma only ends a field when that flag is off.
When you see a quote, flip the flag and add nothing to the value. Always push the field you have accumulated when you hit a separating comma or reach the end of the line.
Splitting the whole line on commas is the obvious first instinct, but it tears quoted fields apart, so it only works once you stitch the broken pieces back together by tracking quote balance.
Scan once with a flag that records whether you are inside quotes. A comma is a separator only when the flag is off, and a quote just toggles the flag and is never copied into the value.