{ }codelper
splitting stringsiterating stringsreading until EOFP0105

Split CSV with quotes

CSV records are given one per line until the end of input. A line is a list of fields separated by commas. A field that starts with a double quote (") is a quoted field.
Its content is what lies between the opening and closing quotes. Inside a quoted field a comma is an ordinary character, not a separator, and "" (two quotes) means one quote character. A closing quote is followed directly by a comma or the end of the line. A field that does not start with a quote is exactly the characters up to the next comma or the end of the line, and contains no quotes. Spaces are part of a field, so do not remove them. Where commas are adjacent (,,) or a line starts or ends with a comma, there is an empty field. For each record, print the number of fields, then one space, then every field wrapped in square brackets and joined together, on one line.

Input
1 to 1,000 lines, each with 1 to 200 characters.
The characters are printable ASCII, and [ and ] never appear.
Every line is valid CSV under the rules above
Output
one line "count [field1][field2]..." per record
Example 1 · stdin
name,"Lee, Mina",42
"say ""hi""",,x,
 a ,b
stdout
3 [name][Lee, Mina][42]
4 [say "hi"][][x][]
2 [ a ][b]
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Splitting on commas (split(",")) also cuts at commas inside quotes.
You need a small state machine that looks at one character at a time and remembers whether it is inside quotes.
Inside quotes, when you meet ", check whether the next character is also ": if so it is one quote character, otherwise the field ends.
If you do not collapse "", you get say ""hi"".
Empty fields have traps per language too.
Python split, JS split and C# Split keep empty fields.
Java String.split(",") drops trailing empty strings, so "a,b," gives 2 (prevent it with split(",", -1)).
C strtok treats adjacent commas as one and skips empty fields entirely.
The C solution here reads one character at a time without strtok.
Python has the standard csv module, so csv.reader(sys.stdin) does it in one line.
C# also has Microsoft.VisualBasic.FileIO.TextFieldParser, but by default it removes spaces at both ends of a field (TrimWhiteSpace is true), so " a " becomes "a"; set TrimWhiteSpace = false if you use it.
Java, JS, TS, C and C++ have no standard CSV tool, so you write the parser yourself.
Reading to the end of input means until Java/C# readLine() returns null, C fgets returns NULL or C++ getline is false.
Craykon reads until Console.ReadLine() is null and looks at one character at a time with s[i].
A quote character is written "\"".

Pythonmain.py · 6 lines
import csvimport sys # csv 모듈이 따옴표 필드, 안의 쉼표, "" → " 를 모두 처리해 준다for fields in csv.reader(sys.stdin):    print(len(fields), "".join(f"[{f}]" for f in fields))
JavaScriptmain.js · 30 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");if (lines.at(-1) === "") lines.pop(); // 마지막 줄 바꿈 뒤의 빈 조각 function parse(s) {  const fields = [];  let i = 0;  while (true) {    let field = "";    if (s[i] === '"') {      i++; // 여는 따옴표      while (true) {        if (s[i] === '"') {          if (s[i + 1] === '"') { field += '"'; i += 2; } // "" → "          else { i++; break; } // 닫는 따옴표        } else field += s[i++];      }    } else {      let j = s.indexOf(",", i);      if (j === -1) j = s.length;      field = s.slice(i, j);      i = j;    }    fields.push(field);    if (i >= s.length) break; // 줄 끝    i++; // 쉼표 건너뛰기(쉼표로 끝나면 다음 바퀴에 빈 필드)  }  return fields;} console.log(lines.map((s) => { const f = parse(s); return `${f.length} ` + f.map((x) => `[${x}]`).join(""); }).join("\n"));
TypeScriptmain.ts · 31 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");if (lines.at(-1) === "") lines.pop(); // 마지막 줄 바꿈 뒤의 빈 조각 function parse(s: string): string[] {  const fields: string[] = [];  let i = 0;  while (true) {    let field = "";    if (s[i] === '"') {      i++; // 여는 따옴표      while (true) {        if (s[i] === '"') {          if (s[i + 1] === '"') { field += '"'; i += 2; } // "" → "          else { i++; break; } // 닫는 따옴표        } else field += s[i++];      }    } else {      let j: number = s.indexOf(",", i);      if (j === -1) j = s.length;      field = s.slice(i, j);      i = j;    }    fields.push(field);    if (i >= s.length) break; // 줄 끝    i++; // 쉼표 건너뛰기(쉼표로 끝나면 다음 바퀴에 빈 필드)  }  return fields;} console.log(lines.map((s: string): string => { const f = parse(s); return `${f.length} ` + f.map((x) => `[${x}]`).join(""); }).join("\n"));
JavaMain.java · 47 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List; public class Main {    static List<String> parse(String s) {        List<String> fields = new ArrayList<>();        int i = 0;        while (true) {            StringBuilder field = new StringBuilder();            if (i < s.length() && s.charAt(i) == '"') {                i++; // 여는 따옴표                while (true) {                    char c = s.charAt(i);                    if (c == '"') {                        if (i + 1 < s.length() && s.charAt(i + 1) == '"') { field.append('"'); i += 2; } // "" → "                        else { i++; break; } // 닫는 따옴표                    } else { field.append(c); i++; }                }            } else {                int j = s.indexOf(',', i);                if (j == -1) j = s.length();                field.append(s, i, j);                i = j;            }            fields.add(field.toString());            if (i >= s.length()) break;            i++; // 쉼표        }        return fields;    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        StringBuilder out = new StringBuilder();        String line;        while ((line = in.readLine()) != null) {            List<String> f = parse(line);            out.append(f.size()).append(' ');            for (String x : f) out.append('[').append(x).append(']');            out.append('\n');        }        System.out.print(out);    }}
C#Main.cs · 54 lines
using System;using System.Collections.Generic;using System.Text; class Program{    static List<string> Parse(string s)    {        var fields = new List<string>();        int i = 0;        while (true)        {            var field = new StringBuilder();            if (i < s.Length && s[i] == '"')            {                i++; // 여는 따옴표                while (true)                {                    if (s[i] == '"')                    {                        if (i + 1 < s.Length && s[i + 1] == '"') { field.Append('"'); i += 2; } // "" → "                        else { i++; break; } // 닫는 따옴표                    }                    else field.Append(s[i++]);                }            }            else            {                int j = s.IndexOf(',', i);                if (j == -1) j = s.Length;                field.Append(s, i, j - i);                i = j;            }            fields.Add(field.ToString());            if (i >= s.Length) break;            i++; // 쉼표        }        return fields;    }     static void Main()    {        var sb = new StringBuilder();        string line;        while ((line = Console.ReadLine()) != null)        {            var f = Parse(line);            sb.Append(f.Count).Append(' ');            foreach (string x in f) sb.Append('[').Append(x).Append(']');            sb.Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 39 lines
#include <iostream>#include <string>#include <vector> static std::vector<std::string> parse(const std::string& s) {    std::vector<std::string> fields;    std::size_t i = 0;    while (true) {        std::string field;        if (i < s.size() && s[i] == '"') {            i++; // 여는 따옴표            while (true) {                if (s[i] == '"') {                    if (i + 1 < s.size() && s[i + 1] == '"') { field += '"'; i += 2; } // "" → "                    else { i++; break; }                                               // 닫는 따옴표                } else field += s[i++];            }        } else {            auto j = s.find(',', i);            if (j == std::string::npos) j = s.size();            field = s.substr(i, j - i);            i = j;        }        fields.push_back(field);        if (i >= s.size()) break;        i++; // 쉼표    }    return fields;} int main() {    std::string line;    while (std::getline(std::cin, line)) {        auto f = parse(line);        std::cout << f.size() << ' ';        for (const auto& x : f) std::cout << '[' << x << ']';        std::cout << '\n';    }}
Cmain.c · 32 lines
#include <stdio.h>#include <string.h> int main(void) {    static char s[512];    static char out[1024];    while (fgets(s, sizeof s, stdin)) {        s[strcspn(s, "\n")] = '\0';        int len = (int)strlen(s), i = 0, count = 0, o = 0;        while (1) {            out[o++] = '[';            if (s[i] == '"') {                i++; /* 여는 따옴표 */                while (1) {                    if (s[i] == '"') {                        if (s[i + 1] == '"') { out[o++] = '"'; i += 2; } /* "" → " */                        else { i++; break; }                              /* 닫는 따옴표 */                    } else out[o++] = s[i++];                }            } else {                while (i < len && s[i] != ',') out[o++] = s[i++];            }            out[o++] = ']';            count++;            if (i >= len) break;            i++; /* 쉼표 */        }        out[o] = '\0';        printf("%d %s\n", count, out);    }    return 0;}
Craykonmain.cray · 63 lines
s = Console.ReadLine();while (s != null){    fields = parseLine(s);    out = fields.Count + " ";    foreach (f in fields)    {        out += "[" + f + "]";    }    Console.WriteLine(out);    s = Console.ReadLine();} // 한 줄을 필드 목록으로: 따옴표 필드 안의 쉼표는 글자, "" 는 따옴표 하나parseLine(s){    fields = [];    i = 0;    while (true)    {        field = "";        if (i < s.Length && s[i] == "\"")        {            i += 1;            while (true)            {                if (s[i] == "\"")                {                    if (i + 1 < s.Length && s[i + 1] == "\"")                    {                        field += "\"";                        i += 2;                    }                    else                    {                        i += 1;                        break;                    }                }                else                {                    field += s[i];                    i += 1;                }            }        }        else        {            while (i < s.Length && s[i] != ",")            {                field += s[i];                i += 1;            }        }        fields.Add(field);        if (i >= s.Length)        {            break;        }        i += 1;    }    return fields;}