Skip to the code
cf.
+25 XP

#629 Split a CSV Row

medium

A spreadsheet import screen previews uploaded CSV files row by row. Commas separate fields, but a field can be wrapped in double quotes so it may contain commas.

Write splitCsvRow(line) that returns the fields of one row. Rules:

  • A " starts a quoted field only when it is the first character of a field. Inside a quoted field, "" stands for one " character, and a single " ends the quoting.
  • After a quoted part ends, any further characters up to the next comma are added to the field as they are. Outside quotes, every character except , is part of the field.
  • An empty line is one empty field, and a trailing comma means a last empty field.

Example 1

Input: line = "name,\"Lima, Ana\",42"
Output: ["name","Lima, Ana","42"]

The comma inside the quotes is part of the field.

Example 2

Input: line = "say,\"He said \"\"hi\"\"\""
Output: ["say","He said \"hi\""]

Two quote characters inside quotes become one.

Constraints

  • 0 <= line.length <= 10^4
  • Quoted fields are always closed.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).