Drill

ProblemsGo › text

Split one CSV line properly

hardtextStringsParsingSimulationGo

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>

Go 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.

Solve it in Python →

Where you start

func parseCsvLine(line string) []string {
	
}

Worked examples

CallResult
parseCsvLine("a,b,c")[]string{"a", "b", "c"}
parseCsvLine("a,\"b,c\",d")[]string{"a", "b,c", "d"}
parseCsvLine("\"say \"\"hi\"\"\",x")[]string{"say \"hi\"", "x"}
parseCsvLine("a,,b")[]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 Go
func parseCsvLine(line string) []string {
	if line == "" {
		return []string{}
	}
	fields := []string{}
	cur := ""
	quoted := false
	i := 0
	for i < len(line) {
		c := line[i]
		if quoted {
			if c == '"' {
				if i+1 < len(line) && line[i+1] == '"' {
					cur += "\""
					i += 2
					continue
				}
				quoted = false
				i++
				continue
			}
			cur += string(c)
			i++
		} else if c == '"' {
			quoted = true
			i++
		} else if c == ',' {
			fields = append(fields, cur)
			cur = ""
			i++
		} else {
			cur += string(c)
			i++
		}
	}
	fields = append(fields, cur)
	return fields
}

The same problem in another language

More text problems in Go