0

Here's my string I got from a csv:

string input = "Volume,447,\"4,325\",142,144";

what I want in my array lines:

447
4,325
142
144

What I tried:

string[] volumes;
if (input.Contains(",\"")) // if they're all double value, it works
     volumes = input.Split(new[] {",\""}, StringSplitOptions.None);
else
     volumes= input.Split(','); // if they're all integer value it works
else
     // what to do if they have both double and integer?
svick
  • 236,525
  • 50
  • 385
  • 514
John
  • 4,351
  • 9
  • 41
  • 57
  • 7
    Sounds like you could do with a decent CSV parser... I wouldn't bother trying to roll your own. – Jon Skeet Jul 20 '13 at 20:12
  • If you got this string from JSON, why don't you deserialize it completely instead of parsing string? Or maybe it will be simplier, if you provide raw JSON for us – Uriil Jul 20 '13 at 20:17
  • @Uriil omg, sorry, my string comes from a csv, not from a json – John Jul 20 '13 at 20:28
  • @JonSkeet yeah, you're right. I'm gonna do that. – John Jul 20 '13 at 20:31
  • @Gui: Here's a simple but efficient that also supports quoting characters: http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader You should avoid the same field- and decimal-separator. – Tim Schmelter Jul 20 '13 at 20:41
  • I ended up using this solution, it's working great. http://stackoverflow.com/questions/3507498/reading-csv-file – John Jul 20 '13 at 20:41

1 Answers1

1

You will need to reference Microsoft.VisualBasic (event if you code in C#) to compile the following code.

    private string[] ParseCsv(string line)
    {
        var parser = new TextFieldParser(new StringReader(line));
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        while (!parser.EndOfData)
        {
            return parser.ReadFields();
        }
        parser.Close();
        return new string[0];
    }
John
  • 4,351
  • 9
  • 41
  • 57
  • [TextFieldParser class](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx) – Jim Mischel Jul 20 '13 at 22:55