2

What is the C# method to split a string with the delimiter as a ',' being careful not to split when the comma is inside a block of text "".

So for example, if the string contains

""AAC","AAC Holdings, Inc.""

the split should return (the [] are there to pretend it is an array element of the string[] returned by split)

[AAC] [AAC Holdings, Inc.]

not

[AAC] [AAC Holdings] [Inc.]
Ivan
  • 7,448
  • 14
  • 69
  • 134

3 Answers3

4

This might probably be best done using Microsoft.VisualBasic library (add this in your reference), Microsoft.VisualBasic.FileIO namespace, TextFieldParser class like this:

using Microsoft.VisualBasic.FileIO;

...

string str = "\"AAC\",\"AAC Holdings, Inc.\"";          

List<string[]> param = new List<string[]>();
string[] words; //add intermediary reference

using (TextFieldParser parser = new TextFieldParser(new StringReader(str))) {
    parser.Delimiters = new string[] { "," }; //the parameter must be comma
    parser.HasFieldsEnclosedInQuotes = true; //VERY IMPORTANT
    while ((words = parser.ReadFields()) != null)
        param.Add(words);
}

foreach (var par in param)
    Console.WriteLine(string.Join("; ", par));

Result:

AAC; AAC Holdings, Inc.

Note that TextFieldParser with HasFieldsEnclosedInQuotes = true is specially designed for case as yours.

Ian
  • 30,182
  • 19
  • 69
  • 107
3

You could split with "," delimiter

var description = "\"AAC\",\"AAC Holdings, Inc.\"";
var listText = description.Split(new[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in listText)
{
    Console.WriteLine(s.Replace("\"",""));
}

Console.ReadLine();

returns

AAC
AAC Holdings, Inc.
TriV
  • 5,118
  • 2
  • 10
  • 18
0

Here is a free library you can use: FileHelpers. I suggest you use a library since it takes care of all these shenanigans for you. Please check out this as well because they load the data to DataTable to accomplish what you need and I will also copy the code here in case that link goes dead:

string path = @"C:\";
using (OleDbConnection conn =
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
            path + @";Extended Properties=""Text;HDR=No;FMT=Delimited"""))
{
    using (OleDbCommand cmd =
        new OleDbCommand("SELECT * FROM verylarge.csv", conn))
    {
        conn.Open();

        using (OleDbDataReader dr =
            cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            while (dr.Read())
            {
                int test1 = dr.GetInt32(0);
                int test2 = dr.GetInt32(1);
                int test3 = dr.GetInt32(2);
                int test4 = dr.GetInt32(3);
                int test5 = dr.GetInt32(4);
            }
        }
    }
}
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64