Separating CSV and excluding commas inside elements

I have a CSV string and I want to split it into an array. However, CSV is a combination of strings and numbers, where strings are enclosed in quotation marks and may contain commas.

For example, I can have CSV as follows:

1,"Hello",2,"World",3,"Hello, World" 

I would like the string to be split into:

 1 "Hello" 2 "World" 3 "Hello, World" 

If I use String.Split(','); , I get:

 1 "Hello" 2 "World" 3 "Hello World" 

Is there an easy way to do this? A library that is already written, or do I need to parse a string character with a character?

+3
source share
4 answers

"Fast CSV reader" in the article "Code Design". I have used it many times.

+6
source

String.Split () for this. Not only does it have unpleasant corner cases when it doesn't work, like the one you just found (and others you haven't seen yet), but the performance is also not perfect. FastCSVReader, published by others, will work, there is a decent csv parser built into the infrastructure (Microsoft.VisualBasic.TextFieldParser), and I have a simple parser that behaves correctly, sent to this question .

+2
source

I would suggest using one of the following solutions: I just tested several of them (hence the delay): -

Hope this helps.

+1
source

This is not the most elegant solution, but the fastest if you just want to copy and paste the code (avoiding the need to import DLLs or other code libraries):

  private string[] splitQuoted(string line, char delimeter) { string[] array; List<string> list = new List<string>(); do { if (line.StartsWith("\"")) { line = line.Substring(1); int idx = line.IndexOf("\""); while (line.IndexOf("\"", idx) == line.IndexOf("\"\"", idx)) { idx = line.IndexOf("\"\"", idx) + 2; } idx = line.IndexOf("\"", idx); list.Add(line.Substring(0, idx)); line = line.Substring(idx + 2); } else { list.Add(line.Substring(0, Math.Max(line.IndexOf(delimeter), 0))); line = line.Substring(line.IndexOf(delimeter) + 1); } } while (line.IndexOf(delimeter) != -1); list.Add(line); array = new string[list.Count]; list.CopyTo(array); return array; } 
+1
source

Source: https://habr.com/ru/post/1492158/


All Articles