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

r1wp621o  于 2023-04-18  发布在  C#
关注(0)|答案(1)|浏览(151)

使用C#,我需要解析一个不是来自文件的CSV字符串。我找到了很多关于解析CSV文件的资料,但几乎没有任何关于字符串的资料。看起来这应该很简单,但到目前为止我只能想出一些效率低下的方法,比如:

using Microsoft.VisualBasic.FileIO;

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

有没有什么好的方法可以让它更高效,更美观?我将处理大量的字符串,所以我不想支付以上所有的费用。谢谢。

bbmckpt7

bbmckpt71#

下面是一个经过简单测试的处理引号的解析器

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

    for (int i = 0; i < line.Length; i++)
    {
        char c = line[i];

        // If the current character is a double quote
        if (c == '"')
        {
            // If we're not inside a quoted section, set isQuoted to true
            if (!isQuoted && sb.Length == 0)
            {
                isQuoted = true;
            }
            else if (isQuoted && i + 1 < line.Length && line[i + 1] == '"') // Check for escaped double quotes
            {
                sb.Append('"');
                i++; // Skip the next quote
            }
            else if (isQuoted) // If the next character is not a double quote, set isQuoted to false
            {
                isQuoted = false;
            }
            else // Not a quoted string
            {
                sb.Append('"');
            }
            continue;
        }

        // If the current character is a comma and we're not inside a quoted section, add the column and clear the StringBuilder
        if (!isQuoted && c == ',')
        {
            columns.Add(sb.ToString());
            sb.Clear();
            continue;
        }

        // Append the character to the current column
        sb.Append(c);
    }

    // Add the last column
    columns.Add(sb.ToString());

    return columns;
}

相关问题