簡體   English   中英

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

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

使用 C#,我需要解析不是來自文件的 CSV 字符串。 我發現了大量關於解析 CSV 文件的資料,但幾乎沒有關於字符串的資料。 似乎這應該很簡單,但到目前為止,我只能提出低效的方法,例如:

using Microsoft.VisualBasic.FileIO;

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

有沒有讓這更高效、更丑陋的好方法? 我將處理大量的字符串,所以我不想支付上述所有費用。 謝謝。

這是一個經過輕微測試的解析器,可以處理引號

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