简体   繁体   English

在 C# 中解析 CSV 字符串(不是文件)

[英]Parsing CSV strings (not files) in C#

Using C#, I need to parse a CSV string that doesn't come from a file.使用 C#,我需要解析不是来自文件的 CSV 字符串。 I've found a great deal of material on parsing CSV files, but virtually nothing on strings.我发现了大量关于解析 CSV 文件的资料,但几乎没有关于字符串的资料。 It seems as though this should be simple, yet thus far I can come up only with inefficient methods, such as this:似乎这应该很简单,但到目前为止,我只能提出低效的方法,例如:

using Microsoft.VisualBasic.FileIO;

var csvParser = new TextFieldParser(new StringReader(strCsvLine));
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;

Are there good ways of making this more efficient and less ugly?有没有让这更高效、更丑陋的好方法? I will be processing huge volumes of strings, so I wouldn't want to pay the cost of all the above.我将处理大量的字符串,所以我不想支付上述所有费用。 Thanks.谢谢。

Here is a lightly tested parser that handles quotes这是一个经过轻微测试的解析器,可以处理引号

List<string> Parse(string line)
{
    var columns = new List<string>();
    var sb = new StringBuilder();

    bool isQuoted = false;
    int nQuotes = 0;
        
    foreach(var c in line)
    {
        if (sb.Length == 0 && !isQuoted && c == '"')
        {
            isQuoted = true;
            continue;
        }
            
        if (isQuoted)
        {
            if (c == '"')
            {
                nQuotes++;
                continue;
            }
            else
            {
                if (nQuotes > 0)
                {
                    sb.Append('"', nQuotes / 2);
                    if (nQuotes % 2 != 0)
                    {
                        isQuoted = false;
                    }
                    nQuotes = 0;
                }
            }
        }
        if (!isQuoted && c == ',')
        {
            columns.Add(sb.ToString());
            sb.Clear();
            continue;
        }

        sb.Append(c);
    }

    if (nQuotes > 0)
    {
        sb.Append('"', nQuotes / 2);
    }

    columns.Add(sb.ToString());

    return columns;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM