How to properly split a CSV using C# split() function?

前端 未结 6 869
旧时难觅i
旧时难觅i 2020-12-05 19:21

Suppose I have this CSV file :

NAME,ADDRESS,DATE
\"Eko S. Wibowo\", \"Tamanan, Banguntapan, Bantul, DIY\", \"6/27/1979\"

I would like like

6条回答
  •  死守一世寂寞
    2020-12-05 19:58

    I've done this with my own method. It simply counts the amout of " and ' characters.
    Improve this to your needs.

        public List SplitCsvLine(string s) {
            int i;
            int a = 0;
            int count = 0;
            List str = new List();
            for (i = 0; i < s.Length; i++) {
                switch (s[i]) {
                    case ',':
                        if ((count & 1) == 0) {
                            str.Add(s.Substring(a, i - a));
                            a = i + 1;
                        }
                        break;
                    case '"':
                    case '\'': count++; break;
                }
            }
            str.Add(s.Substring(a));
            return str;
        }
    

提交回复
热议问题