拆分用逗号分隔的字符串,但不拆分double值

时间:2013-07-20 20:10:01

标签: c#

这是我从csv获得的字符串:

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

我想要的数组行:

447
4,325
142
144

我尝试了什么:

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?

1 个答案:

答案 0 :(得分:1)

您需要引用Microsoft.VisualBasic(如果您使用C#编写代码),以编译以下代码。

    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];
    }