Parse CSV Line with Quoted Fields
Difficulty: Medium · Topics: String Parsing, CSV, State Machine · Acceptance: 100.0% of 1 submissions
Difficulty: Medium | Tags: String Parsing, CSV, State Machine
Description
Given a single line from a CSV file, split it into individual column values. Commas inside double-quoted fields must not be treated as delimiters. Escaped double-quotes within fields are represented as "".
Implement:
parseCSVLine(line) → String[]
Examples
Example 1:
Input: '"John, Doe","30","New York"'
Output: ["John, Doe", "30", "New York"]
Example 2:
Input: 'simple,no quotes,here'
Output: ["simple", "no quotes", "here"]
Example 3 — Escaped quotes:
Input: '"she said ""hello""","42","OK"'
Output: ['she said "hello"', "42", "OK"]
Example 4 — Mixed:
Input: 'Alice,30,"San Francisco, CA"'
Output: ["Alice", "30", "San Francisco, CA"]
Example 5 — Empty fields:
Input: ',,"",""'
Output: ["", "", "", ""]
Constraints
1 <= line.length <= 10^5- Fields may or may not be wrapped in double quotes.
- Commas inside double-quoted fields are literal.
""inside a quoted field represents a single".- No multiline fields (single line only).
Hints
Hint 1
Use a state machine with two states: INSIDE_QUOTES and OUTSIDE_QUOTES. Toggle state on encountering ".
Hint 2
When in OUTSIDE_QUOTES state, a comma splits fields. When INSIDE_QUOTES, a comma is just a character.
---
## SQL & Query Building