Drill

ProblemsTypeScript › text

Split one CSV line properly

hardtextTypeScript

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>

Solve it in the editor →

Where you start

function parseCsvLine(line: string): string[] {
  
}

Worked examples

CallResult
parseCsvLine("a,b,c")["a","b","c"]
parseCsvLine("a,\"b,c\",d")["a","b,c","d"]
parseCsvLine("\"say \"\"hi\"\"\",x")["say \"hi\"","x"]
parseCsvLine("a,,b")["a","","b"]

Hint

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

Reference solution in TypeScript
function parseCsvLine(line: string): string[] {
  if (line === '') return [];
  const fields: string[] = [];
  let cur = '';
  let quoted = false;
  let i = 0;
  while (i < line.length) {
    const c = line[i];
    if (quoted) {
      if (c === '"') {
        if (line[i + 1] === '"') {
          cur += '"';
          i += 2;
          continue;
        }
        quoted = false;
        i++;
        continue;
      }
      cur += c;
      i++;
    } else if (c === '"') {
      quoted = true;
      i++;
    } else if (c === ',') {
      fields.push(cur);
      cur = '';
      i++;
    } else {
      cur += c;
      i++;
    }
  }
  fields.push(cur);
  return fields;
}

The same problem in another language

More text problems in TypeScript